100% found this document useful (1 vote)
667 views5,994 pages

MQL 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
667 views5,994 pages

MQL 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5994

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-2021, MetaQuotes Ltd


2 Content

Content
MQL5 Reference 68
1 Language Basics................................................................................................. 70
Syntax ............................................................................................................................71
Comments......................................................................................................................... 72
I dentifiers......................................................................................................................... 73
Reserved Words
......................................................................................................................... 74
Data Types ............................................................................................................................76
I nteger Types
......................................................................................................................... 77
Char, Short, I................................................................................................................
nt and Long Types 78
Character Constants
................................................................................................................ 82
Datetime Type
................................................................................................................ 85
Color Type ................................................................................................................ 86
Bool Type ................................................................................................................ 87
Enumerations................................................................................................................ 88
Real Types.........................................................................................................................
(double, float) 90
String Type
......................................................................................................................... 95
Structures,
.........................................................................................................................
Classes and I nterfaces 96
Dynamic .........................................................................................................................
Array Object 123
Typecasting
......................................................................................................................... 124
Void Type
.........................................................................................................................
and NULL Constant 129
User-defined
.........................................................................................................................
Types 130
Object Pointers
......................................................................................................................... 140
References:
.........................................................................................................................
Modifier & and Keyword this 143
Operations............................................................................................................................145
and Expressions
Expressions
......................................................................................................................... 146
Arithmetic
.........................................................................................................................
Operations 147
Assignment
.........................................................................................................................
Operations 148
Operations
.........................................................................................................................
of Relation 149
Boolean Operations
......................................................................................................................... 150
Bitwise Operations
......................................................................................................................... 152
Other Operations
......................................................................................................................... 155
Precedence
.........................................................................................................................
Rules 159
Operators ............................................................................................................................161
Compound
.........................................................................................................................
Operator 163
Expression
.........................................................................................................................
Operator 164
Return Operator
......................................................................................................................... 165
Conditional
.........................................................................................................................
Operator if-else 166
Ternary Operator
.........................................................................................................................
?: 167
Switch Operator
......................................................................................................................... 169
Loop Operator
.........................................................................................................................
while 171
Loop Operator
.........................................................................................................................
for 172
Loop Operator
.........................................................................................................................
do while 173
Break Operator
......................................................................................................................... 174
Continue.........................................................................................................................
Operator 175
Object Create
.........................................................................................................................
Operator new 176
Object Delete
.........................................................................................................................
Operator delete 177
Functions ............................................................................................................................178
Function.........................................................................................................................
Call 180
Passing Parameters
......................................................................................................................... 181
Function.........................................................................................................................
Overloading 184
Operation
.........................................................................................................................
Overloading 187
Description
.........................................................................................................................
of External Functions 200
Exporting
.........................................................................................................................
Functions 202

© 2000-2021, MetaQuotes Ltd


3 Content

Event Handling
.........................................................................................................................
Functions 203
Variables ............................................................................................................................214
Local Variables
......................................................................................................................... 216
Formal Parameters
......................................................................................................................... 218
Static Variables
......................................................................................................................... 220
Global Variables
......................................................................................................................... 222
I nput Variables
......................................................................................................................... 223
Extern Variables
......................................................................................................................... 229
z
I nitiali ation
.........................................................................................................................
of Variables 230
Visibility .........................................................................................................................
Scope and Lifetime of Variables 232
Creating.........................................................................................................................
and Deleting Objects 234
............................................................................................................................237
Preprocessor
Macro substitution #
.........................................................................................................................
( define) 239
#
Program.........................................................................................................................
Properties ( property) 242
#
I ncluding.........................................................................................................................
Files ( include) 250
I mporting #
.........................................................................................................................
Functions ( import) 251
Conditional # # # #
.........................................................................................................................
Compilation ( ifdef, ifndef, else, endif) 254
............................................................................................................................256
Object-Oriented Programming
Encapsulation
.........................................................................................................................
and Extensibility of Types 258
I nheritance
......................................................................................................................... 261
Polymorphism
......................................................................................................................... 266
Overload......................................................................................................................... 270
Virtual Functions
......................................................................................................................... 271
Static Members
.........................................................................................................................
of a Class 275
Function.........................................................................................................................
templates 279
Class templates
......................................................................................................................... 283
Abstract.........................................................................................................................
Classes 288
Namespaces............................................................................................................................290
2 Constants, Enumerations
.................................................................................................
and Structures 293
............................................................................................................................294
Chart Constants
Types of .........................................................................................................................
Chart Events 295
Chart Timeframes
......................................................................................................................... 302
Chart Properties
......................................................................................................................... 304
Positioning
.........................................................................................................................
Constants 312
Chart Representation
......................................................................................................................... 313
Examples.........................................................................................................................
of Working with the Chart 315
............................................................................................................................373
Objects Constants
Object Types
......................................................................................................................... 374
OBJ_VLI NE ................................................................................................................ 376
OBJ_HLI NE ................................................................................................................ 381
OBJ_TREND ................................................................................................................ 386
OBJ_TRENDB................................................................................................................
Y ANGLE 393
OBJ_C Y CLES................................................................................................................ 399
OBJ_ARROWED _LI NE
................................................................................................................ 405
OBJ_CHANNEL ................................................................................................................ 411
OBJ_STDDEVCHANNEL
................................................................................................................ 418
OBJ_REGRESSI................................................................................................................
ON 425
OBJ_PI TCHFORK
................................................................................................................ 431
OBJ_GANNLI................................................................................................................
NE 439
OBJ_GANNFAN ................................................................................................................ 446
OBJ_GANNGRI ................................................................................................................
D 453
OBJ_FI BO ................................................................................................................ 460
OBJ_FI BOTI MES
................................................................................................................ 467
OBJ_FI BOFAN................................................................................................................ 474
OBJ_FI BOARC................................................................................................................ 481
OBJ_FI BOCHANNEL
................................................................................................................ 488
OBJ_EX PANSI................................................................................................................
ON 496
OBJ_ELLI OTWAVE5
................................................................................................................ 504

© 2000-2021, MetaQuotes Ltd


4 Content

OBJ_ELLI OTWAVE3
................................................................................................................ 512
OBJ_RECTAN................................................................................................................
GLE 519
OBJ_TRI ANG................................................................................................................
LE 525
OBJ_ELLI PSE................................................................................................................ 532
OBJ_ARROW................................................................................................................
_THUMB_UP 538
OBJ_ARROW................................................................................................................
_THUMB_DOWN 544
OBJ_ARROW................................................................................................................
_UP 550
OBJ_ARROW................................................................................................................
_DOWN 556
OBJ_ARROW................................................................................................................
_STOP 562
OBJ_ARROW................................................................................................................
_CHECK 568
OBJ_ARROW................................................................................................................
_LEFT_PRI CE 574
OBJ_ARROW................................................................................................................
_RI GHT_PRI CE 579
OBJ_ARROW................................................................................................................
_BUY 584
OBJ_ARROW................................................................................................................
_SELL 589
OBJ_ARROW................................................................................................................ 594
OBJ_TEX T ................................................................................................................ 600
OBJ_LABEL ................................................................................................................ 606
OBJ_BUTTON ................................................................................................................ 614
OBJ_CHART ................................................................................................................ 621
OBJ_BI TMAP................................................................................................................ 628
OBJ_BI TMAP................................................................................................................
_LABEL 635
OBJ_EDI T ................................................................................................................ 642
OBJ_EVENT ................................................................................................................ 649
OBJ_RECTAN................................................................................................................
GLE_LABEL 654
Object Properties
......................................................................................................................... 660
Methods .........................................................................................................................
of Object Binding 668
Chart Corner
......................................................................................................................... 673
Visibility .........................................................................................................................
of Objects 676
Levels of.........................................................................................................................
Elliott Wave 679
Gann Objects
......................................................................................................................... 680
Web Colors
......................................................................................................................... 682
Wingdings
......................................................................................................................... 684
............................................................................................................................685
Indicator Constants
Price Constants
......................................................................................................................... 686
Smoothing
.........................................................................................................................
Methods 689
I ndicators
.........................................................................................................................
Lines 690
Drawing .........................................................................................................................
Styles 692
Custom I.........................................................................................................................
ndicator Properties 696
I ndicator.........................................................................................................................
Types 699
Data Type
.........................................................................................................................
I dentifiers 701
............................................................................................................................702
Environment State
Client Terminal
.........................................................................................................................
Properties 703
Running MQL5
.........................................................................................................................
Program Properties 709
Symbol Properties
......................................................................................................................... 712
Account .........................................................................................................................
Properties 739
Testing Statistics
......................................................................................................................... 744
............................................................................................................................748
Trade Constants
History Database
.........................................................................................................................
Properties 749
Order Properties
......................................................................................................................... 750
Position Properties
......................................................................................................................... 757
Deal Properties
......................................................................................................................... 760
Trade Operation
.........................................................................................................................
Types 765
Trade Transaction
.........................................................................................................................
Types 777
Trade Orders
.........................................................................................................................
in DOM 780
Signal Properties
......................................................................................................................... 781
............................................................................................................................783
Named Constants
Predefined
.........................................................................................................................
Macro Substitutions 784
Mathematical
.........................................................................................................................
Constants 790

© 2000-2021, MetaQuotes Ltd


5 Content

Numerical
.........................................................................................................................
Type Constants 792
z
Uninitiali.........................................................................................................................
ation Reason Codes 795
Checking.........................................................................................................................
Object Pointer 797
Other Constants
......................................................................................................................... 798
............................................................................................................................802
Data Structures
Date Type
.........................................................................................................................
Structure 803
I ndicator.........................................................................................................................
Parameter Structure 804
History Data
.........................................................................................................................
Structure 805
Order Book
.........................................................................................................................
Structure 806
q
Trade Re.........................................................................................................................
uest Structure 807
q
Re uest Check
.........................................................................................................................
Result Structure 821
q
Trade Re.........................................................................................................................
uest Result Structure 822
Trade Transaction
.........................................................................................................................
Structure 826
Price Data
.........................................................................................................................
Structure 834
Economic.........................................................................................................................
Сalendar structures 836
............................................................................................................................845
Codes of Errors and Warnings
Trade Server
.........................................................................................................................
Return Codes 846
Compiler .........................................................................................................................
Warnings 850
Compilation
.........................................................................................................................
Errors 854
Runtime Errors
......................................................................................................................... 867
............................................................................................................................881
Input/Output Constants
File Opening
.........................................................................................................................
Flags 882
File Properties
......................................................................................................................... 885
I n-File Position
......................................................................................................................... 886
Use of a Codepage
......................................................................................................................... 887
MessageBox
......................................................................................................................... 888

3 MQL5 programs................................................................................................. 890


............................................................................................................................891
Program Running
............................................................................................................................898
Trade Permission
............................................................................................................................902
Client Terminal Events
Resources ............................................................................................................................905
............................................................................................................................917
Call of Imported Functions
............................................................................................................................919
Runtime Errors
............................................................................................................................920
Testing Trading Strategies
4 Predefined Variables
................................................................................................. 946
_AppliedTo............................................................................................................................947
_Digits ............................................................................................................................949
_Point ............................................................................................................................950
_LastError ............................................................................................................................951
_Period ............................................................................................................................952
_RandomSeed............................................................................................................................953
_StopFlag ............................................................................................................................954
_Symbol ............................................................................................................................955
............................................................................................................................956
_UninitReason
_IsX64 ............................................................................................................................957
5 Common Functions
................................................................................................. 958
Alert ............................................................................................................................960
............................................................................................................................961
CheckPointer
Comment ............................................................................................................................963
CryptEncode............................................................................................................................964
CryptDecode............................................................................................................................966
DebugBreak............................................................................................................................967
............................................................................................................................968
ExpertRemove
GetPointer ............................................................................................................................970
............................................................................................................................974
GetTickCount
............................................................................................................................975
GetTickCount64
............................................................................................................................976
GetMicrosecondCount

© 2000-2021, MetaQuotes Ltd


6 Content

MessageBox............................................................................................................................978
............................................................................................................................979
PeriodSeconds
PlaySound ............................................................................................................................980
Print ............................................................................................................................981
PrintFormat............................................................................................................................983
............................................................................................................................989
ResetLastError
............................................................................................................................990
ResourceCreate
ResourceFree............................................................................................................................992
............................................................................................................................993
ResourceReadImage
ResourceSave............................................................................................................................994
............................................................................................................................995
SetReturnError
SetUserError............................................................................................................................996
Sleep ............................................................................................................................997
............................................................................................................................998
TerminalClose
............................................................................................................................1000
TesterHideIndicators
............................................................................................................................1002
TesterStatistics
TesterStop............................................................................................................................1003
............................................................................................................................1004
TesterDeposit
............................................................................................................................1005
TesterWithdrawal
............................................................................................................................1006
TranslateKey
ZeroMemory............................................................................................................................1007
6 Array Functions
................................................................................................. 1008
............................................................................................................................1010
ArrayBsearch
ArrayCopy............................................................................................................................1014
............................................................................................................................1019
ArrayCompare
ArrayFree............................................................................................................................1020
............................................................................................................................1029
ArrayGetAsSeries
............................................................................................................................1032
ArrayInitialize
ArrayFill ............................................................................................................................1034
............................................................................................................................1036
ArrayIsDynamic
............................................................................................................................1038
ArrayIsSeries
............................................................................................................................1040
ArrayMaximum
............................................................................................................................1051
ArrayMinimum
ArrayPrint............................................................................................................................1062
ArrayRange............................................................................................................................1065
ArrayResiz............................................................................................................................1066
e
............................................................................................................................1069
ArrayInsert
............................................................................................................................1072
ArrayRemove
............................................................................................................................1074
ArrayReverse
............................................................................................................................1076
ArraySetAsSeries
ArraySize ............................................................................................................................1079
ArraySort............................................................................................................................1081
ArraySwap............................................................................................................................1086
7 Conversion Functions
................................................................................................. 1088
............................................................................................................................1090
CharToString
............................................................................................................................1091
CharArrayToString
............................................................................................................................1092
CharArrayToStruct
............................................................................................................................1093
StructToCharArray
............................................................................................................................1094
ColorToARGB
............................................................................................................................1096
ColorToString
............................................................................................................................1097
DoubleToString
............................................................................................................................1098
EnumToString
............................................................................................................................1100
IntegerToString
............................................................................................................................1101
ShortToString
............................................................................................................................1102
ShortArrayToString
............................................................................................................................1103
TimeToString
............................................................................................................................1104
NormalizeDouble
............................................................................................................................1106
StringToCharArray
© 2000-2021, MetaQuotes Ltd
7 Content

............................................................................................................................1107
StringToColor
............................................................................................................................1108
StringToDouble
............................................................................................................................1109
StringToInteger
............................................................................................................................1110
StringToShortArray
............................................................................................................................1111
StringToTime
............................................................................................................................1112
StringFormat
8 Math Functions
................................................................................................. 1116
MathAbs ............................................................................................................................1118
MathArccos............................................................................................................................1119
MathArcsin............................................................................................................................1120
MathArctan............................................................................................................................1121
............................................................................................................................1122
MathArctan2
............................................................................................................................1123
MathClassify
MathCeil ............................................................................................................................1125
MathCos ............................................................................................................................1126
MathExp ............................................................................................................................1127
MathFloor............................................................................................................................1128
MathLog ............................................................................................................................1129
MathLog10............................................................................................................................1130
MathMax ............................................................................................................................1131
MathMin ............................................................................................................................1132
MathMod ............................................................................................................................1133
MathPow ............................................................................................................................1134
MathRand ............................................................................................................................1135
MathRound............................................................................................................................1136
MathSin ............................................................................................................................1137
MathSq rt ............................................................................................................................1138
MathSrand............................................................................................................................1139
MathTan ............................................................................................................................1142
............................................................................................................................1143
MathIsValidNumber
MathExpm1............................................................................................................................1144
MathLog1p............................................................................................................................1145
............................................................................................................................1146
MathArccosh
............................................................................................................................1147
MathArcsinh
............................................................................................................................1148
MathArctanh
MathCosh ............................................................................................................................1149
MathSinh ............................................................................................................................1150
MathTanh ............................................................................................................................1151
MathSwap............................................................................................................................1152
9 String Functions
................................................................................................. 1153
StringAdd ............................................................................................................................1155
............................................................................................................................1157
StringBufferLen
............................................................................................................................1158
StringCompare
............................................................................................................................1160
StringConcatenate
StringFill ............................................................................................................................1161
StringFind............................................................................................................................1162
............................................................................................................................1163
StringGetCharacter
StringInit ............................................................................................................................1164
StringLen ............................................................................................................................1165
............................................................................................................................1166
StringSetLength
............................................................................................................................1167
StringReplace
............................................................................................................................1168
StringReserve
............................................................................................................................1170
StringSetCharacter
StringSplit............................................................................................................................1172
............................................................................................................................1174
StringSubstr
............................................................................................................................1175
StringToLower
............................................................................................................................1176
StringToUpper
............................................................................................................................1177
StringTrimLeft
© 2000-2021, MetaQuotes Ltd
8 Content

............................................................................................................................1178
StringTrimRight
10 Date and Time
................................................................................................. 1179
............................................................................................................................1180
TimeCurrent
............................................................................................................................1181
TimeTradeServer
TimeLocal............................................................................................................................1182
TimeGMT ............................................................................................................................1183
............................................................................................................................1184
TimeDaylightSavings
............................................................................................................................1185
TimeGMTOffset
............................................................................................................................1186
TimeToStruct
............................................................................................................................1187
StructToTime
11 Account Information
................................................................................................. 1188
............................................................................................................................1189
AccountInfoDouble
............................................................................................................................1190
AccountInfoInteger
............................................................................................................................1192
AccountInfoString
12 Checkup ................................................................................................. 1193
............................................................................................................................1194
GetLastError
IsStopped ............................................................................................................................1195
............................................................................................................................1196
UninitializeReason
............................................................................................................................1197
TerminalInfoInteger
............................................................................................................................1198
TerminalInfoDouble
............................................................................................................................1199
TerminalInfoString
............................................................................................................................1200
MQLInfoInteger
............................................................................................................................1201
MQLInfoString
Symbol ............................................................................................................................1202
Period ............................................................................................................................1203
Digits ............................................................................................................................1204
Point ............................................................................................................................1205
13 Event Handling
................................................................................................. 1206
OnStart ............................................................................................................................1208
OnInit ............................................................................................................................1211
OnDeinit ............................................................................................................................1214
OnTick ............................................................................................................................1217
............................................................................................................................1223
OnCalculate
OnTimer ............................................................................................................................1227
OnTrade ............................................................................................................................1230
............................................................................................................................1235
OnTradeTransaction
............................................................................................................................1241
OnBookEvent
............................................................................................................................1244
OnChartEvent
OnTester ............................................................................................................................1251
............................................................................................................................1258
OnTesterInit
............................................................................................................................1265
OnTesterDeinit
............................................................................................................................1266
OnTesterPass
14 Market Info ................................................................................................. 1267
............................................................................................................................1268
SymbolsTotal
............................................................................................................................1269
SymbolExist
............................................................................................................................1270
SymbolName
............................................................................................................................1271
SymbolSelect
............................................................................................................................1272
SymbolIsSynchroni zed
............................................................................................................................1273
SymbolInfoDouble
............................................................................................................................1275
SymbolInfoInteger
............................................................................................................................1277
SymbolInfoString
............................................................................................................................1278
SymbolInfoMarginRate
............................................................................................................................1279
SymbolInfoTick
............................................................................................................................1280
SymbolInfoSessionQuote
............................................................................................................................1281
SymbolInfoSessionTrade
............................................................................................................................1282
MarketBookAdd

© 2000-2021, MetaQuotes Ltd


9 Content

............................................................................................................................1283
MarketBookRelease
............................................................................................................................1284
MarketBookGet
15 Economic Calendar
................................................................................................. 1285
............................................................................................................................1286
CalendarCountryById
............................................................................................................................1288
CalendarEventById
............................................................................................................................1291
CalendarValueById
............................................................................................................................1294
CalendarCountries
............................................................................................................................1296
CalendarEventByCountry
............................................................................................................................1298
CalendarEventByCurrency
............................................................................................................................1300
CalendarValueHistoryByEvent
............................................................................................................................1303
CalendarValueHistory
............................................................................................................................1306
CalendarValueLastByEvent
............................................................................................................................1311
CalendarValueLast
16 Timeseries and
.................................................................................................
Indicators Access 1316
............................................................................................................................1321
Indexing Direction in Arrays, Buffers and Timeseries
Organizing............................................................................................................................1324
Data Access
............................................................................................................................1333
SeriesInfoInteger
Bars ............................................................................................................................1335
............................................................................................................................1338
BarsCalculated
............................................................................................................................1340
IndicatorCreate
............................................................................................................................1342
IndicatorParameters
............................................................................................................................1344
IndicatorRelease
CopyBuffer............................................................................................................................1346
CopyRates............................................................................................................................1351
CopyTime............................................................................................................................1355
CopyOpen............................................................................................................................1358
CopyHigh ............................................................................................................................1361
CopyLow ............................................................................................................................1365
CopyClose............................................................................................................................1368
............................................................................................................................1371
CopyTickVolume
............................................................................................................................1375
CopyRealVolume
CopySpread............................................................................................................................1378
CopyTicks............................................................................................................................1382
............................................................................................................................1388
CopyTicksRange
iBars ............................................................................................................................1390
iBarShift ............................................................................................................................1391
iClose ............................................................................................................................1394
iHigh ............................................................................................................................1396
iHighest ............................................................................................................................1398
iLow ............................................................................................................................1399
iLowest ............................................................................................................................1401
iOpen ............................................................................................................................1402
iTime ............................................................................................................................1404
............................................................................................................................1406
iTickVolume
............................................................................................................................1408
iRealVolume
iVolume ............................................................................................................................1410
iSpread ............................................................................................................................1412
17 Custom Symbols
................................................................................................. 1414
............................................................................................................................1416
CustomSymbolCreate
............................................................................................................................1418
CustomSymbolDelete
............................................................................................................................1419
CustomSymbolSetInteger
............................................................................................................................1420
CustomSymbolSetDouble
............................................................................................................................1421
CustomSymbolSetString
............................................................................................................................1422
CustomSymbolSetMarginRate
............................................................................................................................1423
CustomSymbolSetSessionQuote
............................................................................................................................1424
CustomSymbolSetSessionTrade
............................................................................................................................1425
CustomRatesDelete

© 2000-2021, MetaQuotes Ltd


10 Content

............................................................................................................................1426
CustomRatesReplace
............................................................................................................................1427
CustomRatesUpdate
............................................................................................................................1428
CustomTicksAdd
............................................................................................................................1430
CustomTicksDelete
............................................................................................................................1431
CustomTicksReplace
............................................................................................................................1433
CustomBookAdd
18 Chart Operations
................................................................................................. 1436
............................................................................................................................1438
ChartApplyTemplate
............................................................................................................................1441
ChartSaveTemplate
............................................................................................................................1446
ChartWindowFind
............................................................................................................................1448
ChartTimePriceToXY
............................................................................................................................1449
ChartXYToTimePrice
ChartOpen............................................................................................................................1451
ChartFirst ............................................................................................................................1452
ChartNext............................................................................................................................1453
ChartClose............................................................................................................................1454
ChartSymbol............................................................................................................................1455
ChartPeriod............................................................................................................................1456
ChartRedraw............................................................................................................................1457
............................................................................................................................1458
ChartSetDouble
............................................................................................................................1459
ChartSetInteger
............................................................................................................................1461
ChartSetString
............................................................................................................................1463
ChartGetDouble
............................................................................................................................1465
ChartGetInteger
............................................................................................................................1467
ChartGetString
............................................................................................................................1469
ChartNavigate
ChartID ............................................................................................................................1472
............................................................................................................................1473
ChartIndicatorAdd
............................................................................................................................1477
ChartIndicatorDelete
............................................................................................................................1480
ChartIndicatorGet
............................................................................................................................1482
ChartIndicatorName
............................................................................................................................1483
ChartIndicatorsTotal
............................................................................................................................1484
ChartWindowOnDropped
............................................................................................................................1485
ChartPriceOnDropped
............................................................................................................................1486
ChartTimeOnDropped
............................................................................................................................1487
ChartXOnDropped
............................................................................................................................1488
ChartYOnDropped
............................................................................................................................1489
ChartSetSymbolPeriod
............................................................................................................................1490
ChartScreenShot
19 Trade Functions
................................................................................................. 1493
............................................................................................................................1496
OrderCalcMargin
............................................................................................................................1497
OrderCalcProfit
OrderCheck............................................................................................................................1498
OrderSend............................................................................................................................1499
............................................................................................................................1504
OrderSendAsync
............................................................................................................................1515
PositionsTotal
............................................................................................................................1516
PositionGetSymbol
............................................................................................................................1517
PositionSelect
............................................................................................................................1518
PositionSelectByTicket
............................................................................................................................1519
PositionGetDouble
............................................................................................................................1520
PositionGetInteger
............................................................................................................................1522
PositionGetString
............................................................................................................................1523
PositionGetTicket
............................................................................................................................1524
OrdersTotal
............................................................................................................................1525
OrderGetTicket
............................................................................................................................1527
OrderSelect
............................................................................................................................1528
OrderGetDouble
............................................................................................................................1529
OrderGetInteger
© 2000-2021, MetaQuotes Ltd
11 Content

............................................................................................................................1530
OrderGetString
............................................................................................................................1531
HistorySelect
............................................................................................................................1533
HistorySelectByPosition
............................................................................................................................1534
HistoryOrderSelect
............................................................................................................................1535
HistoryOrdersTotal
............................................................................................................................1536
HistoryOrderGetTicket
............................................................................................................................1538
HistoryOrderGetDouble
............................................................................................................................1539
HistoryOrderGetInteger
............................................................................................................................1542
HistoryOrderGetString
............................................................................................................................1543
HistoryDealSelect
............................................................................................................................1544
HistoryDealsTotal
............................................................................................................................1545
HistoryDealGetTicket
............................................................................................................................1547
HistoryDealGetDouble
............................................................................................................................1548
HistoryDealGetInteger
............................................................................................................................1551
HistoryDealGetString
20 Trade Signals................................................................................................. 1552
............................................................................................................................1553
SignalBaseGetDouble
............................................................................................................................1554
SignalBaseGetInteger
............................................................................................................................1555
SignalBaseGetString
............................................................................................................................1556
SignalBaseSelect
............................................................................................................................1557
SignalBaseTotal
............................................................................................................................1558
SignalInfoGetDouble
............................................................................................................................1559
SignalInfoGetInteger
............................................................................................................................1560
SignalInfoGetString
............................................................................................................................1561
SignalInfoSetDouble
............................................................................................................................1562
SignalInfoSetInteger
............................................................................................................................1563
SignalSubscribe
............................................................................................................................1564
SignalUnSubscribe
21 Network Functions
................................................................................................. 1565
............................................................................................................................1567
SocketCreate
............................................................................................................................1570
SocketClose
............................................................................................................................1573
SocketConnect
............................................................................................................................1577
SocketIsConnected
............................................................................................................................1578
SocketIsReadable
............................................................................................................................1581
SocketIsWritable
............................................................................................................................1582
SocketTimeouts
............................................................................................................................1583
SocketRead
............................................................................................................................1587
SocketSend
............................................................................................................................1591
SocketTlsHandshake
............................................................................................................................1592
SocketTlsCertificate
............................................................................................................................1596
SocketTlsRead
............................................................................................................................1600
SocketTlsReadAvailable
............................................................................................................................1601
SocketTlsSend
............................................................................................................................1602
WebRe q uest
SendFTP ............................................................................................................................1605
SendMail ............................................................................................................................1606
............................................................................................................................1607
SendNotification
22 Global Variables
.................................................................................................
of the Terminal 1608
............................................................................................................................1609
GlobalVariableCheck
............................................................................................................................1610
GlobalVariableTime
............................................................................................................................1611
GlobalVariableDel
............................................................................................................................1612
GlobalVariableGet
............................................................................................................................1613
GlobalVariableName
............................................................................................................................1614
GlobalVariableSet
............................................................................................................................1615
GlobalVariablesFlush
............................................................................................................................1616
GlobalVariableTemp
............................................................................................................................1617
GlobalVariableSetOnCondition

© 2000-2021, MetaQuotes Ltd


12 Content

............................................................................................................................1618
GlobalVariablesDeleteAll
............................................................................................................................1619
GlobalVariablesTotal
23 File Functions................................................................................................. 1620
............................................................................................................................1623
FileSelectDialog
............................................................................................................................1625
FileFindFirst
FileFindNext............................................................................................................................1627
............................................................................................................................1629
FileFindClose
FileIsExist ............................................................................................................................1631
FileOpen ............................................................................................................................1634
FileClose ............................................................................................................................1637
FileCopy ............................................................................................................................1638
FileDelete............................................................................................................................1641
FileMove ............................................................................................................................1643
FileFlush ............................................................................................................................1645
............................................................................................................................1647
FileGetInteger
FileIsEnding............................................................................................................................1650
............................................................................................................................1652
FileIsLineEnding
............................................................................................................................1657
FileReadArray
FileReadBool............................................................................................................................1659
............................................................................................................................1662
FileReadDatetime
............................................................................................................................1665
FileReadDouble
............................................................................................................................1668
FileReadFloat
............................................................................................................................1671
FileReadInteger
FileReadLong............................................................................................................................1675
............................................................................................................................1678
FileReadNumber
............................................................................................................................1683
FileReadString
............................................................................................................................1685
FileReadStruct
FileSeek ............................................................................................................................1689
FileSize ............................................................................................................................1692
FileTell ............................................................................................................................1694
FileWrite ............................................................................................................................1697
............................................................................................................................1700
FileWriteArray
............................................................................................................................1703
FileWriteDouble
............................................................................................................................1706
FileWriteFloat
............................................................................................................................1708
FileWriteInteger
............................................................................................................................1711
FileWriteLong
............................................................................................................................1713
FileWriteString
............................................................................................................................1716
FileWriteStruct
FileLoad ............................................................................................................................1719
FileSave ............................................................................................................................1721
FolderCreate............................................................................................................................1723
FolderDelete............................................................................................................................1726
FolderClean ............................................................................................................................1729
24 Custom Indicators
................................................................................................. 1732
............................................................................................................................1736
Indicator Styles in Examples
_
DRAW NONE
......................................................................................................................... 1743
_
DRAW LI
.........................................................................................................................
NE 1746
DRAW _SECTI
.........................................................................................................................
ON 1750
DRAW _HI STO GRAM
......................................................................................................................... 1754
DRAW _HI STO GRAM2
......................................................................................................................... 1758
DRAW _ARROW
......................................................................................................................... 1762
DRAW _Z.........................................................................................................................
I GZAG 1767
DRAW _FI LLI NG
......................................................................................................................... 1772
DRAW _BARS
......................................................................................................................... 1777
DRAW _CANDLES
......................................................................................................................... 1783
DRAW _COLOR _LI NE
......................................................................................................................... 1789
DRAW _COLOR _SECTI ON
......................................................................................................................... 1794
DRAW _COLOR _HI STO GRAM
......................................................................................................................... 1800

© 2000-2021, MetaQuotes Ltd


13 Content

_
DRAW COLOR _ G
.........................................................................................................................
HI STO RAM2 1805
_
DRAW COLOR _
.........................................................................................................................
ARROW 1810
DRAW _COLOR _ZI GZAG
......................................................................................................................... 1816
DRAW _COLOR _BARS
......................................................................................................................... 1821
DRAW _COLOR _CANDLES
......................................................................................................................... 1828
Connection............................................................................................................................1835
between Indicator Properties and Functions
............................................................................................................................1838
SetIndexBuffer
............................................................................................................................1841
IndicatorSetDouble
............................................................................................................................1845
IndicatorSetInteger
............................................................................................................................1849
IndicatorSetString
............................................................................................................................1852
PlotIndexSetDouble
............................................................................................................................1853
PlotIndexSetInteger
............................................................................................................................1857
PlotIndexSetString
............................................................................................................................1858
PlotIndexGetInteger
25 Object Functions
................................................................................................. 1861
............................................................................................................................1863
ObjectCreate
ObjectName............................................................................................................................1867
............................................................................................................................1868
ObjectDelete
............................................................................................................................1869
ObjectsDeleteAll
ObjectFind............................................................................................................................1870
............................................................................................................................1871
ObjectGetTimeByValue
............................................................................................................................1872
ObjectGetValueByTime
ObjectMove............................................................................................................................1873
............................................................................................................................1874
ObjectsTotal
............................................................................................................................1875
ObjectSetDouble
............................................................................................................................1879
ObjectSetInteger
............................................................................................................................1882
ObjectSetString
............................................................................................................................1884
ObjectGetDouble
............................................................................................................................1886
ObjectGetInteger
............................................................................................................................1888
ObjectGetString
............................................................................................................................1890
TextSetFont
TextOut ............................................................................................................................1892
TextGetSiz............................................................................................................................1896
e
26 Technical Indicators
................................................................................................. 1897
iAC ............................................................................................................................1900
iAD ............................................................................................................................1905
iADX ............................................................................................................................1910
iADXWilder ............................................................................................................................1915
iAlligator ............................................................................................................................1920
iAMA ............................................................................................................................1927
iAO ............................................................................................................................1932
iATR ............................................................................................................................1937
iBearsPower............................................................................................................................1942
iBands ............................................................................................................................1947
iBullsPower............................................................................................................................1953
iCCI ............................................................................................................................1958
iChaikin ............................................................................................................................1963
iCustom ............................................................................................................................1968
iDEMA ............................................................................................................................1972
iDeMarker............................................................................................................................1977
iEnvelopes............................................................................................................................1982
iForce ............................................................................................................................1988
iFractals ............................................................................................................................1993
iFrAMA ............................................................................................................................1998
iGator ............................................................................................................................2003
iIchimoku ............................................................................................................................2010
iBWMFI ............................................................................................................................2017
iMomentum ............................................................................................................................2022
© 2000-2021, MetaQuotes Ltd
14 Content

iMFI ............................................................................................................................2027
iMA ............................................................................................................................2032
iOsMA ............................................................................................................................2037
iMACD ............................................................................................................................2042
iOBV ............................................................................................................................2048
iSAR ............................................................................................................................2053
iRSI ............................................................................................................................2058
iRVI ............................................................................................................................2063
iStdDev ............................................................................................................................2068
iStochastic............................................................................................................................2073
iTEMA ............................................................................................................................2079
iTriX ............................................................................................................................2084
iWPR ............................................................................................................................2089
iVIDyA ............................................................................................................................2094
iVolumes ............................................................................................................................2099
27 Working with.................................................................................................
Optimization Results 2104
FrameFirst............................................................................................................................2105
FrameFilter............................................................................................................................2106
FrameNext............................................................................................................................2107
............................................................................................................................2108
FrameInputs
FrameAdd............................................................................................................................2109
............................................................................................................................2110
ParameterGetRange
............................................................................................................................2113
ParameterSetRange
28 Working with.................................................................................................
Events 2115
............................................................................................................................2116
EventSetMillisecondTimer
............................................................................................................................2117
EventSetTimer
............................................................................................................................2118
EventKillTimer
............................................................................................................................2119
EventChartCustom
29 Working with.................................................................................................
OpenCL 2125
............................................................................................................................2127
CLHandleType
............................................................................................................................2128
CLGetInfoInteger
............................................................................................................................2131
CLGetInfoString
............................................................................................................................2134
CLContextCreate
............................................................................................................................2135
CLContextFree
............................................................................................................................2136
CLGetDeviceInfo
............................................................................................................................2141
CLProgramCreate
............................................................................................................................2146
CLProgramFree
............................................................................................................................2147
CLKernelCreate
............................................................................................................................2148
CLKernelFree
............................................................................................................................2149
CLSetKernelArg
............................................................................................................................2150
CLSetKernelArgMem
............................................................................................................................2151
CLSetKernelArgMemLocal
............................................................................................................................2152
CLBufferCreate
............................................................................................................................2153
CLBufferFree
............................................................................................................................2154
CLBufferWrite
............................................................................................................................2155
CLBufferRead
CLExecute............................................................................................................................2156
............................................................................................................................2158
CLExecutionStatus
30 Working with.................................................................................................
databases 2159
............................................................................................................................2163
DatabaseOpen
............................................................................................................................2165
DatabaseClose
............................................................................................................................2166
DatabaseImport
............................................................................................................................2168
DatabaseExport
............................................................................................................................2170
DatabasePrint
............................................................................................................................2175
DatabaseTableExists
............................................................................................................................2176
DatabaseExecute
............................................................................................................................2188
DatabasePrepare
© 2000-2021, MetaQuotes Ltd
15 Content

............................................................................................................................2197
DatabaseReset
............................................................................................................................2203
DatabaseBind
............................................................................................................................2208
DatabaseBindArray
............................................................................................................................2213
DatabaseRead
............................................................................................................................2214
DatabaseReadBind
............................................................................................................................2218
DatabaseFinali ze
............................................................................................................................2219
DatabaseTransactionBegin
............................................................................................................................2224
DatabaseTransactionCommit
............................................................................................................................2225
DatabaseTransactionRollback
............................................................................................................................2226
DatabaseColumnsCount
............................................................................................................................2227
DatabaseColumnName
............................................................................................................................2228
DatabaseColumnType
............................................................................................................................2229
DatabaseColumnSi ze
............................................................................................................................2230
DatabaseColumnText
............................................................................................................................2231
DatabaseColumnInteger
............................................................................................................................2232
DatabaseColumnLong
............................................................................................................................2233
DatabaseColumnDouble
............................................................................................................................2234
DatabaseColumnBlob
31 Working with.................................................................................................
DirectX 2235
............................................................................................................................2237
DXContextCreate
............................................................................................................................2238
DXContextSetSi ze
............................................................................................................................2239
DXContextGetSi ze
............................................................................................................................2240
DXContextClearColors
............................................................................................................................2241
DXContextClearDepth
............................................................................................................................2242
DXContextGetColors
............................................................................................................................2243
DXContextGetDepth
............................................................................................................................2244
DXBufferCreate
............................................................................................................................2245
DXTextureCreate
............................................................................................................................2252
DXInputCreate
DXInputSet............................................................................................................................2253
............................................................................................................................2254
DXShaderCreate
............................................................................................................................2255
DXShaderSetLayout
............................................................................................................................2256
DXShaderInputsSet
............................................................................................................................2257
DXShaderTexturesSet
DXDraw ............................................................................................................................2258
............................................................................................................................2259
DXDrawIndexed
............................................................................................................................2260
DXPrimiveTopologySet
............................................................................................................................2261
DXBufferSet
............................................................................................................................2262
DXShaderSet
............................................................................................................................2263
DXHandleType
DXRelease............................................................................................................................2264
32 Integration ................................................................................................. 2265
............................................................................................................................2266
MetaTrader for Python
z
initiali e
......................................................................................................................... 2272
login ......................................................................................................................... 2274
shutdown
......................................................................................................................... 2277
version......................................................................................................................... 2278
_
last error
......................................................................................................................... 2280
_
account.........................................................................................................................
info 2282
terminal _
.........................................................................................................................
info 2285
_total
symbols......................................................................................................................... 2288
_get
symbols......................................................................................................................... 2289
symbol_.........................................................................................................................
info 2292
symbol_.........................................................................................................................
info_tick 2296
symbol_.........................................................................................................................
select 2298
market _ book _add
......................................................................................................................... 2302
market _ book _get
......................................................................................................................... 2303
market _ book _release
......................................................................................................................... 2306

© 2000-2021, MetaQuotes Ltd


16 Content

_
copy rates _
.........................................................................................................................
from 2307
_
copy rates _ _
.........................................................................................................................
from pos 2311
copy _rates _range
......................................................................................................................... 2314
copy _ticks _from
......................................................................................................................... 2317
copy _ticks _range
......................................................................................................................... 2320
orders _.........................................................................................................................
total 2323
orders _.........................................................................................................................
get 2324
order _calc _margin
......................................................................................................................... 2327
order _calc _profit
......................................................................................................................... 2330
order _check
......................................................................................................................... 2333
order _send
......................................................................................................................... 2337
positions _total
......................................................................................................................... 2342
positions _get
......................................................................................................................... 2343
history _ orders _total
......................................................................................................................... 2346
history _ orders _get
......................................................................................................................... 2348
history _ deals _total
......................................................................................................................... 2351
history _ deals _get
......................................................................................................................... 2353

33 Standard Library
................................................................................................. 2357
............................................................................................................................2358
Mathematics
Statistics
......................................................................................................................... 2359
Statistical Characteristics
................................................................................................................ 2362
MathMean ........................................................................................................... 2363
MathVariance
........................................................................................................... 2364
MathSkewness
........................................................................................................... 2365
MathKurtosis
........................................................................................................... 2366
MathMoments
........................................................................................................... 2367
MathMedian
........................................................................................................... 2368
MathStandardDeviation
........................................................................................................... 2369
MathAverageDeviation
........................................................................................................... 2370
Normal Distribution
................................................................................................................ 2371
MathProbabilityDensityNormal
........................................................................................................... 2375
MathCumulativeDistributionNormal
........................................................................................................... 2377
MathQuantileNormal
........................................................................................................... 2379
MathRandomNormal
........................................................................................................... 2381
MathMomentsNormal
........................................................................................................... 2382
Log-normal................................................................................................................
distribution 2383
MathProbabilityDensityLognormal
........................................................................................................... 2387
MathCumulativeDistributionLognormal
........................................................................................................... 2389
MathQuantileLognormal
........................................................................................................... 2391
MathRandomLognormal
........................................................................................................... 2393
MathMomentsLognormal
........................................................................................................... 2394
Beta distribution
................................................................................................................ 2395
MathProbabilityDensityBeta
........................................................................................................... 2399
MathCumulativeDistributionBeta
........................................................................................................... 2401
MathQuantileBeta
........................................................................................................... 2403
MathRandomBeta
........................................................................................................... 2405
MathMomentsBeta
........................................................................................................... 2406
Noncentral................................................................................................................
beta distribution 2407
MathProbabilityDensityNoncentralBeta
........................................................................................................... 2411
MathCumulativeDistributionNoncentralBeta
........................................................................................................... 2413
MathQuantileNoncentralBeta
........................................................................................................... 2415
MathRandomNoncentralBeta
........................................................................................................... 2417
MathMomentsNoncentralBeta
........................................................................................................... 2418
Gamma distribution
................................................................................................................ 2419
MathProbabilityDensity Gamma
........................................................................................................... 2423
MathCumulativeDistribution Gamma
........................................................................................................... 2425
MathQuantile Gamma
........................................................................................................... 2427
MathRandom Gamma
........................................................................................................... 2429

© 2000-2021, MetaQuotes Ltd


17 Content

MathMoments G
...........................................................................................................
amma 2430
q
Chi-s uared
................................................................................................................
distribution 2431
MathProbabilityDensityChiS q
...........................................................................................................
uare 2435
MathCumulativeDistributionChiS q
...........................................................................................................
uare 2437
MathQuantileChiS q
...........................................................................................................
uare 2439
MathRandomChiS quare
........................................................................................................... 2441
MathMomentsChiS quare
........................................................................................................... 2442
chi-s quared distribution
Noncentral................................................................................................................ 2443
MathProbabilityDensityNoncentralChiS quare
........................................................................................................... 2447
MathCumulativeDistributionNoncentralChiS quare
........................................................................................................... 2449
MathQuantileNoncentralChiS quare
........................................................................................................... 2451
MathRandomNoncentralChiS quare
........................................................................................................... 2453
MathMomentsNoncentralChiS quare
........................................................................................................... 2454
Exponential
................................................................................................................
distribution 2455
MathProbabilityDensityExponential
........................................................................................................... 2459
MathCumulativeDistributionExponential
........................................................................................................... 2461
MathQuantileExponential
........................................................................................................... 2463
MathRandomExponential
........................................................................................................... 2465
MathMomentsExponential
........................................................................................................... 2466
F-distribution
................................................................................................................ 2467
MathProbabilityDensityF
........................................................................................................... 2471
MathCumulativeDistributionF
........................................................................................................... 2473
MathQuantileF
........................................................................................................... 2475
MathRandomF
........................................................................................................... 2477
MathMomentsF
........................................................................................................... 2478
Noncentral................................................................................................................
F-distribution 2479
MathProbabilityDensityNoncentralF
........................................................................................................... 2483
MathCumulativeDistributionNoncentralF
........................................................................................................... 2485
MathQuantileNoncentralF
........................................................................................................... 2487
MathRandomNoncentralF
........................................................................................................... 2489
MathMomentsNoncentralF
........................................................................................................... 2490
T-distribution
................................................................................................................ 2491
MathProbabilityDensityT
........................................................................................................... 2495
MathCumulativeDistributionT
........................................................................................................... 2497
MathQuantileT
........................................................................................................... 2499
MathRandomT
........................................................................................................... 2501
MathMomentsT
........................................................................................................... 2502
Noncentral................................................................................................................
t-distribution 2503
MathProbabilityDensityNoncentralT
........................................................................................................... 2507
MathCumulativeDistributionNoncentralT
........................................................................................................... 2509
MathQuantileNoncentralT
........................................................................................................... 2511
MathRandomNoncentralT
........................................................................................................... 2513
MathMomentsNoncentralT
........................................................................................................... 2514
Logistic distribution
................................................................................................................ 2515
MathProbabilityDensityLogistic
........................................................................................................... 2519
MathCumulativeDistributionLogistic
........................................................................................................... 2521
MathQuantileLogistic
........................................................................................................... 2523
MathRandomLogistic
........................................................................................................... 2525
MathMomentsLogistic
........................................................................................................... 2526
Cauchy distribution
................................................................................................................ 2527
MathProbabilityDensityCauchy
........................................................................................................... 2531
MathCumulativeDistributionCauchy
........................................................................................................... 2533
MathQuantileCauchy
........................................................................................................... 2535
MathRandomCauchy
........................................................................................................... 2537
MathMomentsCauchy
........................................................................................................... 2538
Uniform distribution
................................................................................................................ 2539
MathProbabilityDensityUniform
........................................................................................................... 2543
MathCumulativeDistributionUniform
........................................................................................................... 2545

© 2000-2021, MetaQuotes Ltd


18 Content

MathQuantileUniform
........................................................................................................... 2547
MathRandomUniform
........................................................................................................... 2549
MathMomentsUniform
........................................................................................................... 2550
Weibull distribution
................................................................................................................ 2551
MathProbabilityDensityWeibull
........................................................................................................... 2555
MathCumulativeDistributionWeibull
........................................................................................................... 2557
MathQuantileWeibull
........................................................................................................... 2559
MathRandomWeibull
........................................................................................................... 2561
MathMomentsWeibull
........................................................................................................... 2562
Binomial distribution
................................................................................................................ 2563
MathProbabilityDensityBinomial
........................................................................................................... 2566
MathCumulativeDistributionBinomial
........................................................................................................... 2568
MathQuantileBinomial
........................................................................................................... 2570
MathRandomBinomial
........................................................................................................... 2572
MathMomentsBinomial
........................................................................................................... 2573
Negative binomial
................................................................................................................
distribution 2574
MathProbabilityDensityNegativeBinomial
........................................................................................................... 2577
MathCumulativeDistributionNegativeBinomial
........................................................................................................... 2579
MathQuantileNegativeBinomial
........................................................................................................... 2581
MathRandomNegativeBinomial
........................................................................................................... 2583
MathMomentsNegativeBinomial
........................................................................................................... 2584
Geometric ................................................................................................................
distribution 2585
MathProbabilityDensity Geometric
........................................................................................................... 2589
MathCumulativeDistribution Geometric
........................................................................................................... 2591
MathQuantile Geometric
........................................................................................................... 2593
MathRandom Geometric
........................................................................................................... 2595
MathMoments Geometric
........................................................................................................... 2596
Hypergeometric
................................................................................................................
distribution 2597
MathProbabilityDensityHypergeometric
........................................................................................................... 2601
MathCumulativeDistributionHypergeometric
........................................................................................................... 2603
MathQuantileHypergeometric
........................................................................................................... 2605
MathRandomHypergeometric
........................................................................................................... 2607
MathMomentsHypergeometric
........................................................................................................... 2608
Poisson distribution
................................................................................................................ 2609
MathProbabilityDensityPoisson
........................................................................................................... 2613
MathCumulativeDistributionPoisson
........................................................................................................... 2615
MathQuantilePoisson
........................................................................................................... 2617
MathRandomPoisson
........................................................................................................... 2619
MathMomentsPoisson
........................................................................................................... 2620
Subfunctions
................................................................................................................ 2621
MathRandomNon Z
...........................................................................................................
ero 2626
MathMoments
........................................................................................................... 2627
MathPowI nt
........................................................................................................... 2628
MathFactorial
........................................................................................................... 2629
MathTrunc........................................................................................................... 2630
MathRound........................................................................................................... 2631
MathArctan2
........................................................................................................... 2633
G
Math amma
........................................................................................................... 2635
G
Math ammaLog
........................................................................................................... 2636
MathBeta ........................................................................................................... 2637
MathBetaLog
........................................................................................................... 2638
MathBetaI ncomplete
........................................................................................................... 2639
G
Math ammaI
...........................................................................................................
ncomplete 2640
MathBinomialCoefficient
........................................................................................................... 2641
MathBinomialCoefficientLog
........................................................................................................... 2642
MathHypergeometric2F2
........................................................................................................... 2643
q
MathSe uence
........................................................................................................... 2644
q
MathSe uenceByCount
........................................................................................................... 2645

© 2000-2021, MetaQuotes Ltd


19 Content

MathReplicate
........................................................................................................... 2646
MathReverse
........................................................................................................... 2647
MathI dentical
........................................................................................................... 2648
MathUni ue q
........................................................................................................... 2649
MathQuickSortAscending
........................................................................................................... 2650
MathQuickSortDescending
........................................................................................................... 2651
MathQuickSort
........................................................................................................... 2652
MathOrder........................................................................................................... 2653
MathBitwiseNot
........................................................................................................... 2654
MathBitwiseAnd
........................................................................................................... 2655
MathBitwiseOr
........................................................................................................... 2656
MathBitwise X
...........................................................................................................
or 2657
MathBitwiseShiftL
........................................................................................................... 2658
MathBitwiseShiftR
........................................................................................................... 2659
MathCumulativeSum
........................................................................................................... 2660
MathCumulativeProduct
........................................................................................................... 2661
MathCumulativeMin
........................................................................................................... 2662
MathCumulativeMax
........................................................................................................... 2663
MathSin ........................................................................................................... 2664
MathCos ........................................................................................................... 2665
MathTan ........................................................................................................... 2666
MathArcsin........................................................................................................... 2667
MathArccos
........................................................................................................... 2668
MathArctan
........................................................................................................... 2669
MathSinPi ........................................................................................................... 2670
MathCosPi ........................................................................................................... 2671
MathTanPi ........................................................................................................... 2672
MathAbs ........................................................................................................... 2673
MathCeil ........................................................................................................... 2674
MathFloor ........................................................................................................... 2675
q
MathS rt ........................................................................................................... 2676
MathExp ........................................................................................................... 2677
MathPow ........................................................................................................... 2678
MathLog ........................................................................................................... 2679
MathLog2 ........................................................................................................... 2680
MathLog10........................................................................................................... 2681
MathLog1p........................................................................................................... 2682
MathDifference
........................................................................................................... 2683
MathSample
........................................................................................................... 2685
MathTukeySummary
........................................................................................................... 2688
MathRange........................................................................................................... 2689
MathMin ........................................................................................................... 2690
MathMax ........................................................................................................... 2691
MathSum ........................................................................................................... 2692
MathProduct
........................................................................................................... 2693
MathStandardDeviation
........................................................................................................... 2694
MathAverageDeviation
........................................................................................................... 2695
MathMedian
........................................................................................................... 2696
MathMean ........................................................................................................... 2697
MathVariance
........................................................................................................... 2698
MathSkewness
........................................................................................................... 2699
MathKurtosis
........................................................................................................... 2700
MathExpm1........................................................................................................... 2701
MathSinh ........................................................................................................... 2702
MathCosh ........................................................................................................... 2703
MathTanh ........................................................................................................... 2704
MathArcsinh
........................................................................................................... 2705
MathArccosh
........................................................................................................... 2706

© 2000-2021, MetaQuotes Ltd


20 Content

MathArctanh
........................................................................................................... 2707
MathSignif ........................................................................................................... 2708
MathRank ........................................................................................................... 2710
MathCorrelationPearson
........................................................................................................... 2711
MathCorrelationSpearman
........................................................................................................... 2712
MathCorrelationKendall
........................................................................................................... 2713
MathQuantile
........................................................................................................... 2714
MathProbabilityDensityEmpirical
........................................................................................................... 2715
MathCumulativeDistributionEmpirical
........................................................................................................... 2716
zz y Logic
Fu ......................................................................................................................... 2717
Membership
................................................................................................................
functions 2718
CConstantMembershipFunction
........................................................................................................... 2720
GetValue ........................................................................................................... 2722
CCompositeMembershipFunction
........................................................................................................... 2723
CompositionType
........................................................................................................... 2725
MembershipFunctions
........................................................................................................... 2725
GetValue ........................................................................................................... 2725
CDifferencTwoSigmoidalMembershipFunction
........................................................................................................... 2727
A1 ........................................................................................................... 2729
A2 ........................................................................................................... 2729
C1 ........................................................................................................... 2730
C2 ........................................................................................................... 2730
GetValue ........................................................................................................... 2731
C Generaliz...........................................................................................................
edBellShapedMembershipFunction 2732
A ........................................................................................................... 2734
B ........................................................................................................... 2734
C ........................................................................................................... 2735
GetValue ........................................................................................................... 2735
CNormalCombinationMembershipFunction
........................................................................................................... 2736
B1 ........................................................................................................... 2738
B2 ........................................................................................................... 2738
Sigma1 ........................................................................................................... 2739
Sigma2 ........................................................................................................... 2739
GetValue ........................................................................................................... 2740
CNormalMembershipFunction
........................................................................................................... 2741
B ........................................................................................................... 2743
Sigma ........................................................................................................... 2743
GetValue ........................................................................................................... 2744
CP_ShapedMembershipFunction
........................................................................................................... 2745
A ........................................................................................................... 2747
B ........................................................................................................... 2747
C ........................................................................................................... 2748
D ........................................................................................................... 2748
GetValue ........................................................................................................... 2749
CProductTwoSigmoidalMembershipFunctions
........................................................................................................... 2750
A1 ........................................................................................................... 2752
A2 ........................................................................................................... 2752
C1 ........................................................................................................... 2753
C2 ........................................................................................................... 2753
GetValue ........................................................................................................... 2754
CS_ShapedMembershipFunction
........................................................................................................... 2755
A ........................................................................................................... 2757
B ........................................................................................................... 2757
GetValue ........................................................................................................... 2758
CSigmoidalMembershipFunction
........................................................................................................... 2759
A ........................................................................................................... 2761
C ........................................................................................................... 2761
GetValue ........................................................................................................... 2762

© 2000-2021, MetaQuotes Ltd


21 Content

z
CTrape oidMembershipFunction
........................................................................................................... 2763
X1 ........................................................................................................... 2765
X2 ........................................................................................................... 2765
X3 ........................................................................................................... 2766
X4 ........................................................................................................... 2766
GetValue ........................................................................................................... 2767
CTriangularMembershipFunction
........................................................................................................... 2768
X1 ........................................................................................................... 2770
X2 ........................................................................................................... 2770
X3 ........................................................................................................... 2771
ToNormalMF
........................................................................................................... 2771
GetValue ........................................................................................................... 2771
C Z_ShapedMembershipFunction
........................................................................................................... 2773
A ........................................................................................................... 2775
B ........................................................................................................... 2775
GetValue ........................................................................................................... 2776
I MembershipFunction
........................................................................................................... 2777
GetValue ........................................................................................................... 2777
zz y systems
Fu ................................................................................................................
rules 2778
CMamdaniFu zz yRule
........................................................................................................... 2779
Conclusion........................................................................................................... 2780
Weight ........................................................................................................... 2780
zz
CSugenoFu...........................................................................................................
yRule 2781
Conclusion........................................................................................................... 2781
CSingleCondition
........................................................................................................... 2783
Not ........................................................................................................... 2783
Term ........................................................................................................... 2784
Var ........................................................................................................... 2784
CConditions
........................................................................................................... 2786
ConditionsList
........................................................................................................... 2786
Not ........................................................................................................... 2787
Op ........................................................................................................... 2787
G
C enericFu zz
...........................................................................................................
yRule 2788
Conclusion........................................................................................................... 2788
Condition ........................................................................................................... 2789
CreateCondition
........................................................................................................... 2789
zz y systems
Fu ................................................................................................................
variables 2791
CFuzz yVariable
........................................................................................................... 2792
AddTerm ........................................................................................................... 2793
GetTermByName
........................................................................................................... 2793
Max ........................................................................................................... 2793
Min ........................................................................................................... 2794
Terms ........................................................................................................... 2794
Values ........................................................................................................... 2795
CSugenoVariable
........................................................................................................... 2796
Functions ........................................................................................................... 2796
GetFuncByName
........................................................................................................... 2797
Values ........................................................................................................... 2797
zz y terms
Fu ................................................................................................................ 2798
MembershipFunction
........................................................................................................... 2799
zz y systems
Fu ................................................................................................................ 2800
Mamdani system
........................................................................................................... 2801
AggregationMethod
........................................................................................................... 2801
Calculate ........................................................................................................... 2802
Defu zz ificationMethod
........................................................................................................... 2802
EmptyRule ........................................................................................................... 2802
I mplicationMethod
........................................................................................................... 2802
Output ........................................................................................................... 2803

© 2000-2021, MetaQuotes Ltd


22 Content

OutputByName
........................................................................................................... 2803
ParseRule ........................................................................................................... 2803
Rules ........................................................................................................... 2803
Sugeno system
........................................................................................................... 2805
Calculate ........................................................................................................... 2805
CreateSugenoFunction
........................................................................................................... 2806
EmptyRule ........................................................................................................... 2807
Output ........................................................................................................... 2807
OutputByName
........................................................................................................... 2807
ParseRule ........................................................................................................... 2807
Rules ........................................................................................................... 2808
OpenCL ............................................................................................................................2809
BufferCreate
......................................................................................................................... 2811
BufferFree
......................................................................................................................... 2812
BufferFromArray
......................................................................................................................... 2813
BufferRead
......................................................................................................................... 2814
BufferWrite
......................................................................................................................... 2815
Execute......................................................................................................................... 2816
GetContext......................................................................................................................... 2817
GetKernel ......................................................................................................................... 2818
GetKernelName
......................................................................................................................... 2819
GetProgram......................................................................................................................... 2820
I nitializ.........................................................................................................................
e 2821
KernelCreate
......................................................................................................................... 2822
KernelFree
......................................................................................................................... 2823
SetArgument
......................................................................................................................... 2824
SetArgumentBuffer
......................................................................................................................... 2825
SetArgumentLocalMemory
......................................................................................................................... 2826
SetBuffersCount
......................................................................................................................... 2827
SetKernelsCount
......................................................................................................................... 2828
Shutdown
......................................................................................................................... 2829
SupportDouble
......................................................................................................................... 2830
Basic Class............................................................................................................................2831
CObject
Prev ......................................................................................................................... 2832
Prev ......................................................................................................................... 2833
Next ......................................................................................................................... 2834
Next ......................................................................................................................... 2835
Compare
......................................................................................................................... 2836
Save ......................................................................................................................... 2838
Load ......................................................................................................................... 2840
Type ......................................................................................................................... 2842
............................................................................................................................2843
Data Collections
CArray ......................................................................................................................... 2844
Step ................................................................................................................ 2846
Step ................................................................................................................ 2847
Total ................................................................................................................ 2848
Available ................................................................................................................ 2849
Max ................................................................................................................ 2850
I sSorted ................................................................................................................ 2851
SortMode ................................................................................................................ 2852
Clear ................................................................................................................ 2853
Sort ................................................................................................................ 2854
Save ................................................................................................................ 2855
Load ................................................................................................................ 2856
CArrayChar
......................................................................................................................... 2857
Reserve ................................................................................................................ 2860
Resi ez ................................................................................................................ 2861
Shutdown ................................................................................................................ 2862

© 2000-2021, MetaQuotes Ltd


23 Content

Add ................................................................................................................ 2863


AddArray ................................................................................................................ 2864
AddArray ................................................................................................................ 2865
I nsert ................................................................................................................ 2867
I nsertArray
................................................................................................................ 2868
I nsertArray
................................................................................................................ 2869
AssignArray
................................................................................................................ 2871
AssignArray
................................................................................................................ 2872
Update ................................................................................................................ 2874
Shift ................................................................................................................ 2875
Delete ................................................................................................................ 2876
DeleteRange
................................................................................................................ 2877
At ................................................................................................................ 2878
CompareArray
................................................................................................................ 2880
CompareArray
................................................................................................................ 2881
I nsertSort ................................................................................................................ 2882
Search ................................................................................................................ 2883
G
Search reat
................................................................................................................ 2884
SearchLess................................................................................................................ 2885
G
Search reatOrE q
................................................................................................................
ual 2886
SearchLessOrE q
................................................................................................................
ual 2887
SearchFirst................................................................................................................ 2888
SearchLast................................................................................................................ 2889
SearchLinear
................................................................................................................ 2890
Save ................................................................................................................ 2891
Load ................................................................................................................ 2892
Type ................................................................................................................ 2894
CArrayShort
......................................................................................................................... 2895
Reserve ................................................................................................................ 2898
Resi ez ................................................................................................................ 2899
Shutdown ................................................................................................................ 2900
Add ................................................................................................................ 2901
AddArray ................................................................................................................ 2902
AddArray ................................................................................................................ 2903
I nsert ................................................................................................................ 2905
I nsertArray
................................................................................................................ 2906
I nsertArray
................................................................................................................ 2907
AssignArray
................................................................................................................ 2909
AssignArray
................................................................................................................ 2910
Update ................................................................................................................ 2912
Shift ................................................................................................................ 2913
Delete ................................................................................................................ 2914
DeleteRange
................................................................................................................ 2915
At ................................................................................................................ 2916
CompareArray
................................................................................................................ 2918
CompareArray
................................................................................................................ 2919
I nsertSort ................................................................................................................ 2920
Search ................................................................................................................ 2921
G
Search reat
................................................................................................................ 2922
SearchLess................................................................................................................ 2923
G
Search reatOrE q
................................................................................................................
ual 2924
SearchLessOrE q
................................................................................................................
ual 2925
SearchFirst................................................................................................................ 2926
SearchLast................................................................................................................ 2927
SearchLinear
................................................................................................................ 2928
Save ................................................................................................................ 2929
Load ................................................................................................................ 2931
Type ................................................................................................................ 2933

© 2000-2021, MetaQuotes Ltd


24 Content

CArrayI.........................................................................................................................
nt 2934
Reserve ................................................................................................................ 2937
Resi ez ................................................................................................................ 2938
Shutdown ................................................................................................................ 2939
Add ................................................................................................................ 2940
AddArray ................................................................................................................ 2941
AddArray ................................................................................................................ 2942
I nsert ................................................................................................................ 2944
I nsertArray
................................................................................................................ 2945
I nsertArray
................................................................................................................ 2946
AssignArray
................................................................................................................ 2948
AssignArray
................................................................................................................ 2949
Update ................................................................................................................ 2951
Shift ................................................................................................................ 2952
Delete ................................................................................................................ 2953
DeleteRange
................................................................................................................ 2954
At ................................................................................................................ 2955
CompareArray
................................................................................................................ 2957
CompareArray
................................................................................................................ 2958
I nsertSort ................................................................................................................ 2959
Search ................................................................................................................ 2960
G
Search reat
................................................................................................................ 2961
SearchLess................................................................................................................ 2962
G
Search reatOrE q
................................................................................................................
ual 2963
SearchLessOrE q
................................................................................................................
ual 2964
SearchFirst................................................................................................................ 2965
SearchLast................................................................................................................ 2966
SearchLinear
................................................................................................................ 2967
Save ................................................................................................................ 2968
Load ................................................................................................................ 2970
Type ................................................................................................................ 2972
CArrayLong
......................................................................................................................... 2973
Reserve ................................................................................................................ 2976
Resi ez ................................................................................................................ 2977
Shutdown ................................................................................................................ 2978
Add ................................................................................................................ 2979
AddArray ................................................................................................................ 2980
AddArray ................................................................................................................ 2981
I nsert ................................................................................................................ 2983
I nsertArray
................................................................................................................ 2984
I nsertArray
................................................................................................................ 2985
AssignArray
................................................................................................................ 2987
AssignArray
................................................................................................................ 2988
Update ................................................................................................................ 2990
Shift ................................................................................................................ 2991
Delete ................................................................................................................ 2992
DeleteRange
................................................................................................................ 2993
At ................................................................................................................ 2994
CompareArray
................................................................................................................ 2996
CompareArray
................................................................................................................ 2997
I nsertSort ................................................................................................................ 2998
Search ................................................................................................................ 2999
G
Search reat
................................................................................................................ 3000
SearchLess................................................................................................................ 3001
G
Search reatOrE q
................................................................................................................
ual 3002
SearchLessOrE q
................................................................................................................
ual 3003
SearchFirst................................................................................................................ 3004
SearchLast................................................................................................................ 3005

© 2000-2021, MetaQuotes Ltd


25 Content

SearchLinear
................................................................................................................ 3006
Save ................................................................................................................ 3007
Load ................................................................................................................ 3009
Type ................................................................................................................ 3011
CArrayFloat
......................................................................................................................... 3012
Delta ................................................................................................................ 3015
Reserve ................................................................................................................ 3016
Resi ez ................................................................................................................ 3017
Shutdown ................................................................................................................ 3018
Add ................................................................................................................ 3019
AddArray ................................................................................................................ 3020
AddArray ................................................................................................................ 3021
I nsert ................................................................................................................ 3023
I nsertArray
................................................................................................................ 3024
I nsertArray
................................................................................................................ 3025
AssignArray
................................................................................................................ 3027
AssignArray
................................................................................................................ 3028
Update ................................................................................................................ 3030
Shift ................................................................................................................ 3031
Delete ................................................................................................................ 3032
DeleteRange
................................................................................................................ 3033
At ................................................................................................................ 3034
CompareArray
................................................................................................................ 3036
CompareArray
................................................................................................................ 3037
I nsertSort ................................................................................................................ 3038
Search ................................................................................................................ 3039
G
Search reat
................................................................................................................ 3040
SearchLess................................................................................................................ 3041
G
Search reatOrE q
................................................................................................................
ual 3042
SearchLessOrE q
................................................................................................................
ual 3043
SearchFirst................................................................................................................ 3044
SearchLast................................................................................................................ 3045
SearchLinear
................................................................................................................ 3046
Save ................................................................................................................ 3047
Load ................................................................................................................ 3049
Type ................................................................................................................ 3051
CArrayDouble
......................................................................................................................... 3052
Delta ................................................................................................................ 3055
Reserve ................................................................................................................ 3056
Resi ez ................................................................................................................ 3057
Shutdown ................................................................................................................ 3058
Add ................................................................................................................ 3059
AddArray ................................................................................................................ 3060
AddArray ................................................................................................................ 3061
I nsert ................................................................................................................ 3063
I nsertArray
................................................................................................................ 3064
I nsertArray
................................................................................................................ 3065
AssignArray
................................................................................................................ 3067
AssignArray
................................................................................................................ 3068
Update ................................................................................................................ 3070
Shift ................................................................................................................ 3071
Delete ................................................................................................................ 3072
DeleteRange
................................................................................................................ 3073
At ................................................................................................................ 3074
CompareArray
................................................................................................................ 3076
CompareArray
................................................................................................................ 3077
Minimum ................................................................................................................ 3078
Maximum ................................................................................................................ 3079

© 2000-2021, MetaQuotes Ltd


26 Content

I nsertSort ................................................................................................................ 3080


Search ................................................................................................................ 3081
G
Search reat
................................................................................................................ 3082
SearchLess................................................................................................................ 3083
G
Search reatOrE q
................................................................................................................
ual 3084
SearchLessOrE q
................................................................................................................
ual 3085
SearchFirst................................................................................................................ 3086
SearchLast................................................................................................................ 3087
SearchLinear
................................................................................................................ 3088
Save ................................................................................................................ 3089
Load ................................................................................................................ 3091
Type ................................................................................................................ 3093
CArrayString
......................................................................................................................... 3094
Reserve ................................................................................................................ 3097
Resi ez ................................................................................................................ 3098
Shutdown ................................................................................................................ 3099
Add ................................................................................................................ 3100
AddArray ................................................................................................................ 3101
AddArray ................................................................................................................ 3102
I nsert ................................................................................................................ 3104
I nsertArray
................................................................................................................ 3105
I nsertArray
................................................................................................................ 3106
AssignArray
................................................................................................................ 3108
AssignArray
................................................................................................................ 3109
Update ................................................................................................................ 3111
Shift ................................................................................................................ 3112
Delete ................................................................................................................ 3113
DeleteRange
................................................................................................................ 3114
At ................................................................................................................ 3115
CompareArray
................................................................................................................ 3117
CompareArray
................................................................................................................ 3118
I nsertSort ................................................................................................................ 3119
Search ................................................................................................................ 3120
G
Search reat
................................................................................................................ 3121
SearchLess................................................................................................................ 3122
G
Search reatOrE q
................................................................................................................
ual 3123
SearchLessOrE q
................................................................................................................
ual 3124
SearchFirst................................................................................................................ 3125
SearchLast................................................................................................................ 3126
SearchLinear
................................................................................................................ 3127
Save ................................................................................................................ 3128
Load ................................................................................................................ 3130
Type ................................................................................................................ 3132
CArrayObj
......................................................................................................................... 3133
FreeMode ................................................................................................................ 3138
FreeMode ................................................................................................................ 3139
Reserve ................................................................................................................ 3141
Resi ez ................................................................................................................ 3142
Clear ................................................................................................................ 3143
Shutdown ................................................................................................................ 3144
CreateElement
................................................................................................................ 3145
Add ................................................................................................................ 3147
AddArray ................................................................................................................ 3148
I nsert ................................................................................................................ 3151
I nsertArray
................................................................................................................ 3153
AssignArray
................................................................................................................ 3155
Update ................................................................................................................ 3157
Shift ................................................................................................................ 3158

© 2000-2021, MetaQuotes Ltd


27 Content

Detach ................................................................................................................ 3159


Delete ................................................................................................................ 3160
DeleteRange
................................................................................................................ 3161
At ................................................................................................................ 3162
CompareArray
................................................................................................................ 3163
I nsertSort ................................................................................................................ 3164
Search ................................................................................................................ 3165
G
Search reat
................................................................................................................ 3166
SearchLess................................................................................................................ 3167
G
Search reatOrE q
................................................................................................................
ual 3168
SearchLessOrE q
................................................................................................................
ual 3170
SearchFirst................................................................................................................ 3171
SearchLast................................................................................................................ 3172
Save ................................................................................................................ 3173
Load ................................................................................................................ 3174
Type ................................................................................................................ 3176
CList ......................................................................................................................... 3177
FreeMode ................................................................................................................ 3180
FreeMode ................................................................................................................ 3181
Total ................................................................................................................ 3183
I sSorted ................................................................................................................ 3184
SortMode ................................................................................................................ 3185
CreateElement
................................................................................................................ 3186
Add ................................................................................................................ 3187
I nsert ................................................................................................................ 3188
DetachCurrent
................................................................................................................ 3190
DeleteCurrent
................................................................................................................ 3191
Delete ................................................................................................................ 3192
Clear ................................................................................................................ 3193
I ndexOf ................................................................................................................ 3194
GetNodeAtI................................................................................................................
ndex 3195
GetFirstNode
................................................................................................................ 3196
GetPrevNode
................................................................................................................ 3197
GetCurrentNode
................................................................................................................ 3198
GetNextNode
................................................................................................................ 3199
GetLastNode
................................................................................................................ 3200
Sort ................................................................................................................ 3201
MoveToI ndex
................................................................................................................ 3202
Exchange ................................................................................................................ 3203
CompareList
................................................................................................................ 3204
Search ................................................................................................................ 3205
Save ................................................................................................................ 3206
Load ................................................................................................................ 3208
Type ................................................................................................................ 3210
CTreeNode
......................................................................................................................... 3211
Owner ................................................................................................................ 3216
Left ................................................................................................................ 3217
Right ................................................................................................................ 3218
Balance ................................................................................................................ 3219
BalanceL ................................................................................................................ 3220
BalanceR ................................................................................................................ 3221
CreateSample
................................................................................................................ 3222
RefreshBalance
................................................................................................................ 3223
GetNext ................................................................................................................ 3224
SaveNode ................................................................................................................ 3225
LoadNode ................................................................................................................ 3226
Type ................................................................................................................ 3227
CTree ......................................................................................................................... 3228

© 2000-2021, MetaQuotes Ltd


28 Content

Root ................................................................................................................ 3234


CreateElement
................................................................................................................ 3235
I nsert ................................................................................................................ 3236
Detach ................................................................................................................ 3237
Delete ................................................................................................................ 3238
Clear ................................................................................................................ 3239
Find ................................................................................................................ 3240
Save ................................................................................................................ 3241
Load ................................................................................................................ 3242
Type ................................................................................................................ 3243
............................................................................................................................3244
Generic Data Collections
I Collection < >
.........................................................................................................................
T 3247
Add ................................................................................................................ 3248
Count ................................................................................................................ 3249
Contains ................................................................................................................ 3250
CopyTo ................................................................................................................ 3251
Clear ................................................................................................................ 3252
Remove ................................................................................................................ 3253
q
I E ualityComparable < >
.........................................................................................................................
T 3254
q
E uals ................................................................................................................ 3255
HashCode ................................................................................................................ 3256
I Comparable < >
.........................................................................................................................
T 3257
Compare ................................................................................................................ 3258
I Comparer < >
.........................................................................................................................
T 3259
Compare ................................................................................................................ 3260
q
I E ualityComparer < >
.........................................................................................................................
T 3261
q
E uals ................................................................................................................ 3262
HashCode ................................................................................................................ 3263
< >
I List T ......................................................................................................................... 3264
G
Try etValue
................................................................................................................ 3265
TrySetValue
................................................................................................................ 3266
I nsert ................................................................................................................ 3267
I ndexOf ................................................................................................................ 3268
LastI ndexOf
................................................................................................................ 3269
RemoveAt ................................................................................................................ 3270
<
I Map TKey,TValue >
......................................................................................................................... 3271
Add ................................................................................................................ 3272
Contains ................................................................................................................ 3273
Remove ................................................................................................................ 3274
G
Try etValue
................................................................................................................ 3275
TrySetValue
................................................................................................................ 3276
CopyTo ................................................................................................................ 3277
< >
I Set T ......................................................................................................................... 3278
ExceptWith
................................................................................................................ 3280
I ntersectWith
................................................................................................................ 3281
SymmetricExceptWith
................................................................................................................ 3282
UnionWith ................................................................................................................ 3283
I sProperSubsetOf
................................................................................................................ 3284
I sProperSupersetOf
................................................................................................................ 3285
I sSubsetOf................................................................................................................ 3286
I sSupersetOf
................................................................................................................ 3287
Overlaps ................................................................................................................ 3288
q
SetE uals ................................................................................................................ 3289
CDefaultComparer < >
.........................................................................................................................
T 3290
Compare ................................................................................................................ 3291
CDefaultE q < >
.........................................................................................................................
ualityComparer T 3292
q
E uals ................................................................................................................ 3293
HashCode ................................................................................................................ 3294

© 2000-2021, MetaQuotes Ltd


29 Content

CRedBlackTreeNode < >


.........................................................................................................................
T 3295
Value ................................................................................................................ 3296
Parent ................................................................................................................ 3297
Left ................................................................................................................ 3298
Right ................................................................................................................ 3299
Color ................................................................................................................ 3300
I sLeaf ................................................................................................................ 3301
CreateEmptyNode
................................................................................................................ 3302
CLinkedListNode < >
.........................................................................................................................
T 3303
List ................................................................................................................ 3304
Next ................................................................................................................ 3305
Previous ................................................................................................................ 3306
Value ................................................................................................................ 3307
CKeyValuePair < >
.........................................................................................................................
TKey,TValue 3308
Key ................................................................................................................ 3309
Value ................................................................................................................ 3310
Clone ................................................................................................................ 3311
Compare ................................................................................................................ 3312
q
E uals ................................................................................................................ 3313
HashCode ................................................................................................................ 3314
CArrayList < >
.........................................................................................................................
T 3315
Capacity ................................................................................................................ 3317
Count ................................................................................................................ 3318
Contains ................................................................................................................ 3319
TrimExcess................................................................................................................ 3320
G
Try etValue
................................................................................................................ 3321
TrySetValue
................................................................................................................ 3322
Add ................................................................................................................ 3323
AddRange ................................................................................................................ 3324
I nsert ................................................................................................................ 3325
I nsertRange
................................................................................................................ 3326
CopyTo ................................................................................................................ 3327
BinarySearch
................................................................................................................ 3328
I ndexOf ................................................................................................................ 3329
LastI ndexOf
................................................................................................................ 3330
Clear ................................................................................................................ 3331
Remove ................................................................................................................ 3332
RemoveAt ................................................................................................................ 3333
RemoveRange
................................................................................................................ 3334
Reverse ................................................................................................................ 3335
Sort ................................................................................................................ 3336
CHashMap < >
.........................................................................................................................
TKey,TValue 3337
Add ................................................................................................................ 3339
Count ................................................................................................................ 3340
Comparer ................................................................................................................ 3341
Contains ................................................................................................................ 3342
ContainsKey
................................................................................................................ 3343
ContainsValue
................................................................................................................ 3344
CopyTo ................................................................................................................ 3345
Clear ................................................................................................................ 3346
Remove ................................................................................................................ 3347
G
Try etValue
................................................................................................................ 3348
TrySetValue
................................................................................................................ 3349
CHashSet < >
.........................................................................................................................
T 3350
Add ................................................................................................................ 3352
Count ................................................................................................................ 3353
Contains ................................................................................................................ 3354
Comparer ................................................................................................................ 3355

© 2000-2021, MetaQuotes Ltd


30 Content

TrimExcess................................................................................................................ 3356
CopyTo ................................................................................................................ 3357
Clear ................................................................................................................ 3358
Remove ................................................................................................................ 3359
ExceptWith
................................................................................................................ 3360
I ntersectWith
................................................................................................................ 3361
SymmetricExceptWith
................................................................................................................ 3362
UnionWith ................................................................................................................ 3363
I sProperSubsetOf
................................................................................................................ 3364
I sProperSupersetOf
................................................................................................................ 3365
I sSubsetOf................................................................................................................ 3366
I sSupersetOf
................................................................................................................ 3367
Overlaps ................................................................................................................ 3368
q
SetE uals ................................................................................................................ 3369
CLinkedList < >
.........................................................................................................................
T 3370
Add ................................................................................................................ 3372
AddAfter ................................................................................................................ 3373
AddBefore ................................................................................................................ 3374
AddFirst ................................................................................................................ 3375
AddLast ................................................................................................................ 3376
Count ................................................................................................................ 3377
Head ................................................................................................................ 3378
First ................................................................................................................ 3379
Last ................................................................................................................ 3380
Contains ................................................................................................................ 3381
CopyTo ................................................................................................................ 3382
Clear ................................................................................................................ 3383
Remove ................................................................................................................ 3384
RemoveFirst
................................................................................................................ 3385
RemoveLast
................................................................................................................ 3386
Find ................................................................................................................ 3387
FindLast ................................................................................................................ 3388
T < >
CQueue......................................................................................................................... 3389
Add ................................................................................................................ 3390
q
En ueue ................................................................................................................ 3391
Count ................................................................................................................ 3392
Contains ................................................................................................................ 3393
TrimExcess................................................................................................................ 3394
CopyTo ................................................................................................................ 3395
Clear ................................................................................................................ 3396
Remove ................................................................................................................ 3397
q
De ueue ................................................................................................................ 3398
Peek ................................................................................................................ 3399
CRedBlackTree < >
.........................................................................................................................
T 3400
Add ................................................................................................................ 3402
Count ................................................................................................................ 3403
Root ................................................................................................................ 3404
Contains ................................................................................................................ 3405
Comparer ................................................................................................................ 3406
G
Try etMin ................................................................................................................ 3407
G
Try etMax................................................................................................................ 3408
CopyTo ................................................................................................................ 3409
Clear ................................................................................................................ 3410
Remove ................................................................................................................ 3411
RemoveMin................................................................................................................ 3412
RemoveMax................................................................................................................ 3413
Find ................................................................................................................ 3414
FindMin ................................................................................................................ 3415

© 2000-2021, MetaQuotes Ltd


31 Content

FindMax ................................................................................................................ 3416


CSortedMap < >
.........................................................................................................................
TKey, TValue 3417
Add ................................................................................................................ 3419
Count ................................................................................................................ 3420
Comparer ................................................................................................................ 3421
Contains ................................................................................................................ 3422
ContainsKey
................................................................................................................ 3423
ContainsValue
................................................................................................................ 3424
CopyTo ................................................................................................................ 3425
Clear ................................................................................................................ 3426
Remove ................................................................................................................ 3427
G
Try etValue
................................................................................................................ 3428
TrySetValue
................................................................................................................ 3429
CSortedSet < >
.........................................................................................................................
T 3430
Add ................................................................................................................ 3432
Count ................................................................................................................ 3433
Contains ................................................................................................................ 3434
Comparer ................................................................................................................ 3435
G
Try etMin ................................................................................................................ 3436
G
Try etMax................................................................................................................ 3437
CopyTo ................................................................................................................ 3438
Clear ................................................................................................................ 3439
Remove ................................................................................................................ 3440
ExceptWith
................................................................................................................ 3441
I ntersectWith
................................................................................................................ 3442
SymmetricExceptWith
................................................................................................................ 3443
UnionWith ................................................................................................................ 3444
I sProperSubsetOf
................................................................................................................ 3445
I sProperSupersetOf
................................................................................................................ 3446
I sSubsetOf................................................................................................................ 3447
I sSupersetOf
................................................................................................................ 3448
Overlaps ................................................................................................................ 3449
q
SetE uals ................................................................................................................ 3450
GetViewBetween................................................................................................................ 3451
GetReverse................................................................................................................ 3452
CStack <.........................................................................................................................
T> 3453
Add ................................................................................................................ 3454
Count ................................................................................................................ 3455
Contains ................................................................................................................ 3456
TrimExcess................................................................................................................ 3457
CopyTo ................................................................................................................ 3458
Clear ................................................................................................................ 3459
Remove ................................................................................................................ 3460
Push ................................................................................................................ 3461
Peek ................................................................................................................ 3462
Pop ................................................................................................................ 3463
ArrayBinarySearch < >
.........................................................................................................................
T 3464
ArrayI ndexOf < >
.........................................................................................................................
T 3465
ArrayLastI < >
.........................................................................................................................
ndexOf T 3466
ArrayReverse < >
.........................................................................................................................
T 3467
Compare
......................................................................................................................... 3468
q < >
E uals T
......................................................................................................................... 3471
GetHashCode
......................................................................................................................... 3472
Files ............................................................................................................................3475
CFile ......................................................................................................................... 3476
Handle ................................................................................................................ 3478
Filename ................................................................................................................ 3479
Flags ................................................................................................................ 3480

© 2000-2021, MetaQuotes Ltd


32 Content

SetUnicode................................................................................................................ 3481
SetCommon................................................................................................................ 3482
Open ................................................................................................................ 3483
Close ................................................................................................................ 3484
Delete ................................................................................................................ 3485
I sExist ................................................................................................................ 3486
Copy ................................................................................................................ 3487
Move ................................................................................................................ 3488
z
Si e ................................................................................................................ 3489
Tell ................................................................................................................ 3490
Seek ................................................................................................................ 3491
Flush ................................................................................................................ 3492
I sEnding ................................................................................................................ 3493
I sLineEnding
................................................................................................................ 3494
FolderCreate
................................................................................................................ 3495
FolderDelete
................................................................................................................ 3496
FolderClean................................................................................................................ 3497
FileFindFirst
................................................................................................................ 3498
FileFindNext
................................................................................................................ 3499
FileFindClose
................................................................................................................ 3500
CFileBin......................................................................................................................... 3501
Open ................................................................................................................ 3503
WriteChar ................................................................................................................ 3504
WriteShort................................................................................................................ 3505
WriteI nteger
................................................................................................................ 3506
WriteLong ................................................................................................................ 3507
WriteFloat ................................................................................................................ 3508
WriteDouble
................................................................................................................ 3509
WriteString
................................................................................................................ 3510
WriteCharArray
................................................................................................................ 3511
WriteShortArray
................................................................................................................ 3512
WriteI ntegerArray
................................................................................................................ 3513
WriteLongArray
................................................................................................................ 3514
WriteFloatArray
................................................................................................................ 3515
WriteDoubleArray
................................................................................................................ 3516
WriteObject
................................................................................................................ 3517
ReadChar ................................................................................................................ 3518
ReadShort ................................................................................................................ 3519
ReadI nteger
................................................................................................................ 3520
ReadLong ................................................................................................................ 3521
ReadFloat ................................................................................................................ 3522
ReadDouble................................................................................................................ 3523
ReadString ................................................................................................................ 3524
ReadCharArray
................................................................................................................ 3525
ReadShortArray
................................................................................................................ 3526
ReadI ntegerArray
................................................................................................................ 3527
ReadLongArray
................................................................................................................ 3528
ReadFloatArray
................................................................................................................ 3529
ReadDoubleArray
................................................................................................................ 3530
ReadObject
................................................................................................................ 3531
CFileTxt......................................................................................................................... 3532
Open ................................................................................................................ 3533
WriteString
................................................................................................................ 3534
ReadString ................................................................................................................ 3535
Strings ............................................................................................................................3536
CString ......................................................................................................................... 3537
Str ................................................................................................................ 3539
Len ................................................................................................................ 3540

© 2000-2021, MetaQuotes Ltd


33 Content

Copy ................................................................................................................ 3541


Fill ................................................................................................................ 3542
Assign ................................................................................................................ 3543
Append ................................................................................................................ 3544
I nsert ................................................................................................................ 3545
Compare ................................................................................................................ 3546
CompareNoCase
................................................................................................................ 3547
Left ................................................................................................................ 3548
Right ................................................................................................................ 3549
Mid ................................................................................................................ 3550
Trim ................................................................................................................ 3551
TrimLeft ................................................................................................................ 3552
TrimRight ................................................................................................................ 3553
Clear ................................................................................................................ 3554
ToUpper ................................................................................................................ 3555
ToLower ................................................................................................................ 3556
Reverse ................................................................................................................ 3557
Find ................................................................................................................ 3558
FindRev ................................................................................................................ 3559
Remove ................................................................................................................ 3560
Replace ................................................................................................................ 3561
............................................................................................................................3562
Graphic Objects
CChartObject
......................................................................................................................... 3563
ChartI d ................................................................................................................ 3566
Window ................................................................................................................ 3567
Name ................................................................................................................ 3568
NumPoints ................................................................................................................ 3569
Attach ................................................................................................................ 3570
SetPoint ................................................................................................................ 3571
Delete ................................................................................................................ 3572
Detach ................................................................................................................ 3573
ShiftObject................................................................................................................ 3574
ShiftPoint ................................................................................................................ 3575
Time ................................................................................................................ 3576
Price ................................................................................................................ 3578
Color ................................................................................................................ 3580
Style ................................................................................................................ 3581
Width ................................................................................................................ 3582
Background
................................................................................................................ 3583
Selected ................................................................................................................ 3584
Selectable ................................................................................................................ 3585
Description................................................................................................................ 3586
Tooltip ................................................................................................................ 3587
Timeframes................................................................................................................ 3588
Z_Order ................................................................................................................ 3589
CreateTime................................................................................................................ 3590
LevelsCount
................................................................................................................ 3591
LevelColor ................................................................................................................ 3592
LevelStyle ................................................................................................................ 3594
LevelWidth................................................................................................................ 3596
LevelValue ................................................................................................................ 3598
LevelDescription
................................................................................................................ 3600
GetI nteger................................................................................................................ 3602
SetI nteger ................................................................................................................ 3604
GetDouble ................................................................................................................ 3606
SetDouble ................................................................................................................ 3608
GetString ................................................................................................................ 3610
SetString ................................................................................................................ 3612

© 2000-2021, MetaQuotes Ltd


34 Content

Save ................................................................................................................ 3614


Load ................................................................................................................ 3615
Type ................................................................................................................ 3616
Line Objects
......................................................................................................................... 3617
CChartObjectVLine
................................................................................................................ 3618
Create ........................................................................................................... 3619
Type ........................................................................................................... 3620
CChartObjectHLine
................................................................................................................ 3621
Create ........................................................................................................... 3622
Type ........................................................................................................... 3623
CChartObjectTrend
................................................................................................................ 3624
Create ........................................................................................................... 3626
RayLeft ........................................................................................................... 3627
RayRight ........................................................................................................... 3628
Save ........................................................................................................... 3629
Load ........................................................................................................... 3630
Type ........................................................................................................... 3631
CChartObjectTrendByAngle
................................................................................................................ 3632
Create ........................................................................................................... 3634
Angle ........................................................................................................... 3635
Type ........................................................................................................... 3636
CChartObjectCycles
................................................................................................................ 3637
Create ........................................................................................................... 3638
Type ........................................................................................................... 3639
Channel.........................................................................................................................
Objects 3640
CChartObjectChannel
................................................................................................................ 3641
Create ........................................................................................................... 3643
Type ........................................................................................................... 3644
CChartObjectRegression
................................................................................................................ 3645
Create ........................................................................................................... 3647
Type ........................................................................................................... 3648
CChartObjectStdDevChannel
................................................................................................................ 3649
Create ........................................................................................................... 3651
Deviations ........................................................................................................... 3652
Save ........................................................................................................... 3653
Load ........................................................................................................... 3654
Type ........................................................................................................... 3655
CChartObjectPitchfork
................................................................................................................ 3656
Create ........................................................................................................... 3658
Type ........................................................................................................... 3659
Gann Tools
......................................................................................................................... 3660
CChartObject GannLine
................................................................................................................ 3661
Create ........................................................................................................... 3663
PipsPerBar........................................................................................................... 3664
Save ........................................................................................................... 3665
Load ........................................................................................................... 3666
Type ........................................................................................................... 3667
CChartObject G
................................................................................................................
annFan 3668
Create ........................................................................................................... 3670
PipsPerBar........................................................................................................... 3671
Downtrend........................................................................................................... 3672
Save ........................................................................................................... 3673
Load ........................................................................................................... 3674
Type ........................................................................................................... 3675
CChartObject G G
................................................................................................................
ann rid 3676
Create ........................................................................................................... 3678
PipsPerBar........................................................................................................... 3679
Downtrend........................................................................................................... 3680

© 2000-2021, MetaQuotes Ltd


35 Content

Save ........................................................................................................... 3681


Load ........................................................................................................... 3682
Type ........................................................................................................... 3683
Fibonacci
.........................................................................................................................
Tools 3684
CChartObjectFibo
................................................................................................................ 3685
Create ........................................................................................................... 3687
Type ........................................................................................................... 3688
CChartObjectFiboTimes
................................................................................................................ 3689
Create ........................................................................................................... 3690
Type ........................................................................................................... 3691
CChartObjectFiboFan
................................................................................................................ 3692
Create ........................................................................................................... 3693
Type ........................................................................................................... 3694
CChartObjectFiboArc
................................................................................................................ 3695
Create ........................................................................................................... 3697
Scale ........................................................................................................... 3698
Ellipse ........................................................................................................... 3699
Save ........................................................................................................... 3700
Load ........................................................................................................... 3701
Type ........................................................................................................... 3702
CChartObjectFiboChannel
................................................................................................................ 3703
Create ........................................................................................................... 3705
Type ........................................................................................................... 3706
CChartObjectFiboExpansion
................................................................................................................ 3707
Create ........................................................................................................... 3709
Type ........................................................................................................... 3710
Elliott Tools
......................................................................................................................... 3711
CChartObjectElliottWave3
................................................................................................................ 3712
Create ........................................................................................................... 3714
Degree ........................................................................................................... 3715
Lines ........................................................................................................... 3716
Save ........................................................................................................... 3717
Load ........................................................................................................... 3718
Type ........................................................................................................... 3719
CChartObjectElliottWave5
................................................................................................................ 3720
Create ........................................................................................................... 3722
Type ........................................................................................................... 3724
Shape Objects
......................................................................................................................... 3725
CChartObjectRectangle
................................................................................................................ 3726
Create ........................................................................................................... 3727
Type ........................................................................................................... 3728
CChartObjectTriangle
................................................................................................................ 3729
Create ........................................................................................................... 3730
Type ........................................................................................................... 3731
CChartObjectEllipse
................................................................................................................ 3732
Create ........................................................................................................... 3733
Type ........................................................................................................... 3734
Arrow Objects
......................................................................................................................... 3735
CChartObjectArrow
................................................................................................................ 3736
Create ........................................................................................................... 3738
ArrowCode........................................................................................................... 3740
Anchor ........................................................................................................... 3742
Save ........................................................................................................... 3744
Load ........................................................................................................... 3745
Type ........................................................................................................... 3746
Arrows with
................................................................................................................
fixed code 3747
Create ........................................................................................................... 3749
ArrowCode........................................................................................................... 3751

© 2000-2021, MetaQuotes Ltd


36 Content

Type ........................................................................................................... 3752


Control.........................................................................................................................
Objects 3753
CChartObjectText
................................................................................................................ 3754
Create ........................................................................................................... 3756
Angle ........................................................................................................... 3757
Font ........................................................................................................... 3758
FontSi ez ........................................................................................................... 3759
Anchor ........................................................................................................... 3760
Save ........................................................................................................... 3761
Load ........................................................................................................... 3762
Type ........................................................................................................... 3763
CChartObjectLabel
................................................................................................................ 3764
Create ........................................................................................................... 3766
X_Distance........................................................................................................... 3767
Y_Distance........................................................................................................... 3768
X_Siz e ........................................................................................................... 3769
Y_Siz e ........................................................................................................... 3770
Corner ........................................................................................................... 3771
Time ........................................................................................................... 3772
Price ........................................................................................................... 3773
Save ........................................................................................................... 3774
Load ........................................................................................................... 3775
Type ........................................................................................................... 3776
CChartObjectEdit
................................................................................................................ 3777
Create ........................................................................................................... 3779
TextAlign ........................................................................................................... 3780
X_Siz e ........................................................................................................... 3781
Y_Siz e ........................................................................................................... 3782
BackColor ........................................................................................................... 3783
BorderColor
........................................................................................................... 3784
ReadOnly ........................................................................................................... 3785
Angle ........................................................................................................... 3786
Save ........................................................................................................... 3787
Load ........................................................................................................... 3788
Type ........................................................................................................... 3789
CChartObjectButton
................................................................................................................ 3790
State ........................................................................................................... 3792
Save ........................................................................................................... 3793
Load ........................................................................................................... 3794
Type ........................................................................................................... 3795
CChartObjectSubChart
................................................................................................................ 3796
Create ........................................................................................................... 3798
X_Distance........................................................................................................... 3799
Y_Distance........................................................................................................... 3800
Corner ........................................................................................................... 3801
X_Siz e ........................................................................................................... 3802
Y_Siz e ........................................................................................................... 3803
Symbol ........................................................................................................... 3804
Period ........................................................................................................... 3805
Scale ........................................................................................................... 3806
DateScale ........................................................................................................... 3807
PriceScale ........................................................................................................... 3808
Time ........................................................................................................... 3809
Price ........................................................................................................... 3810
Save ........................................................................................................... 3811
Load ........................................................................................................... 3812
Type ........................................................................................................... 3813
CChartObjectBitmap
................................................................................................................ 3814

© 2000-2021, MetaQuotes Ltd


37 Content

Create ........................................................................................................... 3816


BmpFile ........................................................................................................... 3817
X_Offset ........................................................................................................... 3818
Y_Offset ........................................................................................................... 3819
Save ........................................................................................................... 3820
Load ........................................................................................................... 3821
Type ........................................................................................................... 3822
CChartObjectBmpLabel
................................................................................................................ 3823
Create ........................................................................................................... 3825
X_Distance........................................................................................................... 3826
Y_Distance........................................................................................................... 3827
X_Offset ........................................................................................................... 3828
Y_Offset ........................................................................................................... 3829
Corner ........................................................................................................... 3830
X_Siz e ........................................................................................................... 3831
Y_Siz e ........................................................................................................... 3832
BmpFileOn ........................................................................................................... 3833
BmpFileOff........................................................................................................... 3834
State ........................................................................................................... 3835
Time ........................................................................................................... 3836
Price ........................................................................................................... 3837
Save ........................................................................................................... 3838
Load ........................................................................................................... 3839
Type ........................................................................................................... 3840
CChartObjectRectLabel
................................................................................................................ 3841
Create ........................................................................................................... 3843
X_Siz e ........................................................................................................... 3844
Y_Siz e ........................................................................................................... 3845
BackColor ........................................................................................................... 3846
Angle ........................................................................................................... 3847
BorderType
........................................................................................................... 3848
Save ........................................................................................................... 3849
Load ........................................................................................................... 3850
Type ........................................................................................................... 3851
............................................................................................................................3852
Custom Graphics
CCanvas
......................................................................................................................... 3853
Attach ................................................................................................................ 3857
Arc ................................................................................................................ 3858
Pie ................................................................................................................ 3862
FillPolygon ................................................................................................................ 3866
FillEllipse ................................................................................................................ 3867
GetDefaultColor
................................................................................................................ 3868
ChartObjectName
................................................................................................................ 3869
Circle ................................................................................................................ 3870
CircleAA ................................................................................................................ 3871
CircleWu ................................................................................................................ 3872
Create ................................................................................................................ 3873
CreateBitmap
................................................................................................................ 3874
CreateBitmapLabel
................................................................................................................ 3876
Destroy ................................................................................................................ 3878
Ellipse ................................................................................................................ 3879
EllipseAA ................................................................................................................ 3880
EllipseWu ................................................................................................................ 3881
Erase ................................................................................................................ 3882
Fill ................................................................................................................ 3883
FillCircle ................................................................................................................ 3884
FillRectangle
................................................................................................................ 3885
FillTriangle ................................................................................................................ 3886

© 2000-2021, MetaQuotes Ltd


38 Content

et G
FontAngle ................................................................................................................ 3887
FontAngleSet
................................................................................................................ 3888
et G
FontFlags ................................................................................................................ 3889
FontFlagsSet
................................................................................................................ 3890
Font etG ................................................................................................................ 3891
et G
FontName ................................................................................................................ 3892
FontNameSet
................................................................................................................ 3893
FontSet ................................................................................................................ 3894
z G
FontSi e et
................................................................................................................ 3895
FontSiz eSet
................................................................................................................ 3896
Height ................................................................................................................ 3897
Line ................................................................................................................ 3898
LineAA ................................................................................................................ 3899
LineWu ................................................................................................................ 3900
LineHori ontal z
................................................................................................................ 3901
LineVertical
................................................................................................................ 3902
LineStyleSet
................................................................................................................ 3903
LineThick ................................................................................................................ 3904
LineThickVertical
................................................................................................................ 3905
LineThickHori z
................................................................................................................
ontal 3906
LoadFromFile
................................................................................................................ 3907
G
Pixel et ................................................................................................................ 3908
PixelSet ................................................................................................................ 3909
PixelSetAA ................................................................................................................ 3910
Polygon ................................................................................................................ 3911
PolygonAA ................................................................................................................ 3912
PolygonWu................................................................................................................ 3913
PolygonThick
................................................................................................................ 3914
PolygonSmooth
................................................................................................................ 3915
Polyline ................................................................................................................ 3916
PolylineSmooth
................................................................................................................ 3917
PolylineThick
................................................................................................................ 3918
PolylineWu ................................................................................................................ 3919
PolylineAA ................................................................................................................ 3920
Rectangle ................................................................................................................ 3921
z
Resi e ................................................................................................................ 3922
ResourceName
................................................................................................................ 3923
TextHeight................................................................................................................ 3924
TextOut ................................................................................................................ 3925
TextSi e z ................................................................................................................ 3926
TextWidth ................................................................................................................ 3927
TransparentLevelSet
................................................................................................................ 3928
Triangle ................................................................................................................ 3929
TriangleAA ................................................................................................................ 3930
TriangleWu................................................................................................................ 3931
Update ................................................................................................................ 3932
Width ................................................................................................................ 3933
CChartCanvas
......................................................................................................................... 3934
ColorBackground
................................................................................................................ 3938
ColorBorder
................................................................................................................ 3939
ColorText ................................................................................................................ 3940
G
Color rid ................................................................................................................ 3941
MaxData ................................................................................................................ 3942
MaxDescrLen
................................................................................................................ 3943
ShowFlags ................................................................................................................ 3944
I sShowLegend
................................................................................................................ 3945
I sShowScaleLeft
................................................................................................................ 3946
I sShowScaleRight
................................................................................................................ 3947

© 2000-2021, MetaQuotes Ltd


39 Content

I sShowScaleTop
................................................................................................................ 3948
I sShowScaleBottom
................................................................................................................ 3949
G
I sShow rid................................................................................................................ 3950
I sShowDescriptors
................................................................................................................ 3951
I sShowPercent
................................................................................................................ 3952
VScaleMin ................................................................................................................ 3953
VScaleMax ................................................................................................................ 3954
G
Num rid ................................................................................................................ 3955
DataOffset................................................................................................................ 3956
DataTotal ................................................................................................................ 3957
DrawDescriptors
................................................................................................................ 3958
DrawData ................................................................................................................ 3959
Create ................................................................................................................ 3960
AllowedShowFlags
................................................................................................................ 3961
ShowLegend
................................................................................................................ 3962
ShowScaleLeft
................................................................................................................ 3963
ShowScaleRight
................................................................................................................ 3964
ShowScaleTop
................................................................................................................ 3965
ShowScaleBottom
................................................................................................................ 3966
G
Show rid ................................................................................................................ 3967
ShowDescriptors
................................................................................................................ 3968
ShowValue ................................................................................................................ 3969
ShowPercent
................................................................................................................ 3970
LegendAlignment
................................................................................................................ 3971
Accumulative
................................................................................................................ 3972
VScaleParams
................................................................................................................ 3973
DescriptorUpdate
................................................................................................................ 3974
ColorUpdate
................................................................................................................ 3975
ValuesCheck
................................................................................................................ 3976
Redraw ................................................................................................................ 3977
DrawBackground
................................................................................................................ 3978
DrawLegend
................................................................................................................ 3979
DrawLegendVertical
................................................................................................................ 3980
DrawLegendHori z
................................................................................................................
ontal 3981
CalcScales ................................................................................................................ 3982
DrawScales................................................................................................................ 3983
DrawScaleLeft
................................................................................................................ 3984
DrawScaleRight
................................................................................................................ 3985
DrawScaleTop
................................................................................................................ 3986
DrawScaleBottom
................................................................................................................ 3987
G
Draw rid ................................................................................................................ 3988
DrawChart................................................................................................................ 3989
CHistogramChart
......................................................................................................................... 3990
Gradient ................................................................................................................ 3995
Bar Gap ................................................................................................................ 3996
BarMinSiz e................................................................................................................ 3997
BarBorder ................................................................................................................ 3998
Create ................................................................................................................ 3999
SeriesAdd ................................................................................................................ 4000
SeriesI nsert
................................................................................................................ 4001
SeriesUpdate
................................................................................................................ 4002
SeriesDelete
................................................................................................................ 4003
ValueUpdate
................................................................................................................ 4004
DrawData ................................................................................................................ 4005
DrawBar ................................................................................................................ 4006
GradientBrush
................................................................................................................ 4007
CLineChart
......................................................................................................................... 4008
Filled ................................................................................................................ 4012

© 2000-2021, MetaQuotes Ltd


40 Content

Create ................................................................................................................ 4013


SeriesAdd ................................................................................................................ 4014
SeriesI nsert
................................................................................................................ 4015
SeriesUpdate
................................................................................................................ 4016
SeriesDelete
................................................................................................................ 4017
ValueUpdate
................................................................................................................ 4018
DrawChart................................................................................................................ 4019
DrawData ................................................................................................................ 4020
CalcArea ................................................................................................................ 4021
CPieChart
......................................................................................................................... 4022
Create ................................................................................................................ 4026
SeriesSet ................................................................................................................ 4027
ValueAdd ................................................................................................................ 4028
ValueI nsert................................................................................................................ 4029
ValueUpdate
................................................................................................................ 4030
ValueDelete
................................................................................................................ 4031
DrawChart................................................................................................................ 4032
DrawPie ................................................................................................................ 4033
LabelMake ................................................................................................................ 4034
............................................................................................................................4035
3D Graphics
CCanvas3D
......................................................................................................................... 4036
AmbientColor G
................................................................................................................
et 4038
AmbientColorSet
................................................................................................................ 4039
Attach ................................................................................................................ 4040
Create ................................................................................................................ 4041
Destroy ................................................................................................................ 4042
X
D Context................................................................................................................ 4043
D X Dispatcher
................................................................................................................ 4044
I nputScene................................................................................................................ 4045
et G
LightColor ................................................................................................................ 4046
LightColorSet
................................................................................................................ 4047
LightDirection G
................................................................................................................
et 4048
LightDirectionSet
................................................................................................................ 4049
ObjectAdd ................................................................................................................ 4050
ProjectionMatrix G
................................................................................................................
et 4051
ProjectionMatrixSet
................................................................................................................ 4052
Render ................................................................................................................ 4053
RenderBegin
................................................................................................................ 4054
RenderEnd ................................................................................................................ 4055
et G
ViewMatrix................................................................................................................ 4056
ViewMatrixSet
................................................................................................................ 4057
ViewPositionSet
................................................................................................................ 4058
ViewRotationSet
................................................................................................................ 4059
ViewTargetSet
................................................................................................................ 4060
ViewUpDirectionSet
................................................................................................................ 4061
............................................................................................................................4062
Price Charts
ChartI D......................................................................................................................... 4067
Mode ......................................................................................................................... 4068
Foreground
......................................................................................................................... 4069
Shift ......................................................................................................................... 4070
z
ShiftSi e
......................................................................................................................... 4071
AutoScroll
......................................................................................................................... 4072
Scale ......................................................................................................................... 4073
ScaleFix......................................................................................................................... 4074
11_
ScaleFix......................................................................................................................... 4075
FixedMax
......................................................................................................................... 4076
FixedMin
......................................................................................................................... 4077
PointsPerBar
......................................................................................................................... 4078

© 2000-2021, MetaQuotes Ltd


41 Content

ScalePPB
......................................................................................................................... 4079
ShowOHLC
......................................................................................................................... 4080
ShowLineBid
......................................................................................................................... 4081
ShowLineAsk
......................................................................................................................... 4082
ShowLastLine
......................................................................................................................... 4083
ShowPeriodSep
......................................................................................................................... 4084
G
Show rid
......................................................................................................................... 4085
ShowVolumes
......................................................................................................................... 4086
ShowObjectDescr
......................................................................................................................... 4087
ShowDateScale
......................................................................................................................... 4088
ShowPriceScale
......................................................................................................................... 4089
ColorBackground
......................................................................................................................... 4090
ColorForeground
......................................................................................................................... 4091
G
Color rid
......................................................................................................................... 4092
ColorBarUp
......................................................................................................................... 4093
ColorBarDown
......................................................................................................................... 4094
ColorCandleBull
......................................................................................................................... 4095
ColorCandleBear
......................................................................................................................... 4096
ColorChartLine
......................................................................................................................... 4097
ColorVolumes
......................................................................................................................... 4098
ColorLineBid
......................................................................................................................... 4099
ColorLineAsk
......................................................................................................................... 4100
ColorLineLast
......................................................................................................................... 4101
ColorStopLevels
......................................................................................................................... 4102
VisibleBars
......................................................................................................................... 4103
WindowsTotal
......................................................................................................................... 4104
WindowI
.........................................................................................................................
sVisible 4105
WindowHandle
......................................................................................................................... 4106
FirstVisibleBar
......................................................................................................................... 4107
WidthI nBars
......................................................................................................................... 4108
WidthI nPixels
......................................................................................................................... 4109
HeightI nPixels
......................................................................................................................... 4110
PriceMin
......................................................................................................................... 4111
PriceMax
......................................................................................................................... 4112
Attach ......................................................................................................................... 4113
FirstChart
......................................................................................................................... 4114
NextChart
......................................................................................................................... 4115
Open ......................................................................................................................... 4116
Detach ......................................................................................................................... 4117
Close ......................................................................................................................... 4118
BringToTop
......................................................................................................................... 4119
EventObjectCreate
......................................................................................................................... 4120
EventObjectDelete
......................................................................................................................... 4121
I ndicatorAdd
......................................................................................................................... 4122
I ndicatorDelete
......................................................................................................................... 4123
I ndicatorsTotal
......................................................................................................................... 4124
I ndicatorName
......................................................................................................................... 4125
Navigate
......................................................................................................................... 4126
Symbol ......................................................................................................................... 4127
Period ......................................................................................................................... 4128
Redraw......................................................................................................................... 4129
GetI nteger
......................................................................................................................... 4130
SetI nteger
......................................................................................................................... 4131
GetDouble
......................................................................................................................... 4132
SetDouble
......................................................................................................................... 4133
GetString
......................................................................................................................... 4134
SetString
......................................................................................................................... 4135
SetSymbolPeriod
......................................................................................................................... 4136

© 2000-2021, MetaQuotes Ltd


42 Content

ApplyTemplate
......................................................................................................................... 4137
ScreenShot
......................................................................................................................... 4138
WindowOnDropped
......................................................................................................................... 4139
PriceOnDropped
......................................................................................................................... 4140
TimeOnDropped
......................................................................................................................... 4141
X OnDropped
......................................................................................................................... 4142
Y OnDropped
......................................................................................................................... 4143
Save ......................................................................................................................... 4144
Load ......................................................................................................................... 4145
Type ......................................................................................................................... 4146
Scientific ............................................................................................................................4147
Charts
GraphPlot
......................................................................................................................... 4148
CAxis ......................................................................................................................... 4152
AutoScale ................................................................................................................ 4154
Min ................................................................................................................ 4155
Max ................................................................................................................ 4156
Step ................................................................................................................ 4157
Name ................................................................................................................ 4158
Color ................................................................................................................ 4159
z
ValuesSi e ................................................................................................................ 4160
ValuesWidth
................................................................................................................ 4161
ValuesFormat
................................................................................................................ 4162
ValuesDateTimeMode
................................................................................................................ 4163
ValuesFunctionFormat
................................................................................................................ 4164
ValuesFunctionFormatCBData
................................................................................................................ 4166
z
NameSi e ................................................................................................................ 4167
ZeroLever ................................................................................................................ 4168
DefaultStep
................................................................................................................ 4169
MaxLabels ................................................................................................................ 4170
G
Min race ................................................................................................................ 4171
G
Max race ................................................................................................................ 4172
SelectAxisScale
................................................................................................................ 4173
G
CColor .........................................................................................................................
enerator 4174
Next ................................................................................................................ 4175
Reset ................................................................................................................ 4176
CCurve......................................................................................................................... 4177
Type ................................................................................................................ 4179
Name ................................................................................................................ 4180
Color ................................................................................................................ 4181
X Max ................................................................................................................ 4182
X Min ................................................................................................................ 4183
Y Max ................................................................................................................ 4184
Y Min ................................................................................................................ 4185
Siz e ................................................................................................................ 4186
z
PointsSi e ................................................................................................................ 4187
PointsFill ................................................................................................................ 4188
PointsColor................................................................................................................ 4189
Get X ................................................................................................................ 4190
Get Y ................................................................................................................ 4191
LinesStyle ................................................................................................................ 4192
LinesI sSmooth
................................................................................................................ 4193
LinesSmoothTension
................................................................................................................ 4194
LinesSmoothStep
................................................................................................................ 4195
LinesEndStyle
................................................................................................................ 4196
LinesWidth................................................................................................................ 4197
HistogramWidth
................................................................................................................ 4199
CustomPlotCBData
................................................................................................................ 4200
CustomPlotFunction
................................................................................................................ 4201

© 2000-2021, MetaQuotes Ltd


43 Content

PointsType................................................................................................................ 4205
StepsDimension
................................................................................................................ 4206
TrendLineCoefficients
................................................................................................................ 4207
TrendLineColor
................................................................................................................ 4208
TrendLineVisible
................................................................................................................ 4209
Update ................................................................................................................ 4211
Visible ................................................................................................................ 4213
G
C raphic
......................................................................................................................... 4214
Create ................................................................................................................ 4217
Destroy ................................................................................................................ 4218
Update ................................................................................................................ 4219
ChartObjectName
................................................................................................................ 4220
ResourceName
................................................................................................................ 4221
X Axis ................................................................................................................ 4222
Y Axis ................................................................................................................ 4223
GapSiz e ................................................................................................................ 4224
BackgroundColor
................................................................................................................ 4225
BackgroundMain
................................................................................................................ 4226
BackgroundMainSi z
................................................................................................................
e 4227
BackgroundMainColor
................................................................................................................ 4228
BackgroundSub
................................................................................................................ 4229
BackgroundSubSi z
................................................................................................................
e 4230
BackgroundSubColor
................................................................................................................ 4231
GridLineColor
................................................................................................................ 4232
GridBackgroundColor
................................................................................................................ 4233
GridCircleRadius
................................................................................................................ 4234
GridCircleColor
................................................................................................................ 4235
GridHasCircle
................................................................................................................ 4236
GridAxisLineColor
................................................................................................................ 4237
HistoryNameWidth
................................................................................................................ 4238
HistoryNameSi z
................................................................................................................
e 4239
HistorySymbolSi z
................................................................................................................
e 4240
TextAdd ................................................................................................................ 4241
LineAdd ................................................................................................................ 4242
CurveAdd ................................................................................................................ 4243
CurvePlot ................................................................................................................ 4246
CurvePlotAll
................................................................................................................ 4247
G
Curve etByI
................................................................................................................
ndex 4248
G
Curve etByName
................................................................................................................ 4249
CurveRemoveByI
................................................................................................................
ndex 4250
CurveRemoveByName
................................................................................................................ 4251
CurvesTotal
................................................................................................................ 4252
MarksToAxisAdd
................................................................................................................ 4253
MajorMarkSi z
................................................................................................................
e 4254
FontSet ................................................................................................................ 4255
G
Font et ................................................................................................................ 4256
Attach ................................................................................................................ 4257
CalculateMaxMinValues
................................................................................................................ 4258
Height ................................................................................................................ 4259
I ndentDown
................................................................................................................ 4260
I ndentLeft ................................................................................................................ 4261
I ndentRight
................................................................................................................ 4262
I ndentUp ................................................................................................................ 4263
Redraw ................................................................................................................ 4264
ResetParameters
................................................................................................................ 4265
Scale X ................................................................................................................ 4266
Scale Y ................................................................................................................ 4267
SetDefaultParameters
................................................................................................................ 4268

© 2000-2021, MetaQuotes Ltd


44 Content

Width ................................................................................................................ 4269


Indicators............................................................................................................................4270
Base classes
......................................................................................................................... 4271
CSpreadBuffer
................................................................................................................ 4272
z
Si e ........................................................................................................... 4274
SetSymbolPeriod
........................................................................................................... 4275
At ........................................................................................................... 4276
Refresh ........................................................................................................... 4277
RefreshCurrent
........................................................................................................... 4278
CTimeBuffer
................................................................................................................ 4279
z
Si e ........................................................................................................... 4281
SetSymbolPeriod
........................................................................................................... 4282
At ........................................................................................................... 4283
Refresh ........................................................................................................... 4284
RefreshCurrent
........................................................................................................... 4285
CTickVolumeBuffer
................................................................................................................ 4286
z
Si e ........................................................................................................... 4288
SetSymbolPeriod
........................................................................................................... 4289
At ........................................................................................................... 4290
Refresh ........................................................................................................... 4291
RefreshCurrent
........................................................................................................... 4292
CRealVolumeBuffer
................................................................................................................ 4293
z
Si e ........................................................................................................... 4295
SetSymbolPeriod
........................................................................................................... 4296
At ........................................................................................................... 4297
Refresh ........................................................................................................... 4298
RefreshCurrent
........................................................................................................... 4299
CDoubleBuffer
................................................................................................................ 4300
z
Si e ........................................................................................................... 4302
SetSymbolPeriod
........................................................................................................... 4303
At ........................................................................................................... 4304
Refresh ........................................................................................................... 4305
RefreshCurrent
........................................................................................................... 4306
COpenBuffer
................................................................................................................ 4307
Refresh ........................................................................................................... 4308
RefreshCurrent
........................................................................................................... 4309
CHighBuffer
................................................................................................................ 4310
Refresh ........................................................................................................... 4311
RefreshCurrent
........................................................................................................... 4312
CLowBuffer................................................................................................................ 4313
Refresh ........................................................................................................... 4314
RefreshCurrent
........................................................................................................... 4315
CCloseBuffer
................................................................................................................ 4316
Refresh ........................................................................................................... 4317
RefreshCurrent
........................................................................................................... 4318
CI ndicatorBuffer
................................................................................................................ 4319
Offset ........................................................................................................... 4321
Name ........................................................................................................... 4322
At ........................................................................................................... 4323
Refresh ........................................................................................................... 4324
RefreshCurrent
........................................................................................................... 4325
CSeries ................................................................................................................ 4326
Name ........................................................................................................... 4328
BuffersTotal
........................................................................................................... 4329
Timeframe ........................................................................................................... 4330
Symbol ........................................................................................................... 4331
Period ........................................................................................................... 4332
RefreshCurrent
........................................................................................................... 4333

© 2000-2021, MetaQuotes Ltd


45 Content

z
BufferSi e ........................................................................................................... 4334
e z
BufferResi ........................................................................................................... 4335
Refresh ........................................................................................................... 4336
PeriodDescription
........................................................................................................... 4337
CPriceSeries
................................................................................................................ 4338
e z
BufferResi ........................................................................................................... 4340
GetData ........................................................................................................... 4341
Refresh ........................................................................................................... 4342
MinI ndex ........................................................................................................... 4343
MinValue ........................................................................................................... 4344
MaxI ndex ........................................................................................................... 4345
MaxValue ........................................................................................................... 4346
CI ndicator ................................................................................................................ 4347
Handle ........................................................................................................... 4349
Status ........................................................................................................... 4350
FullRelease........................................................................................................... 4351
Create ........................................................................................................... 4352
e z
BufferResi ........................................................................................................... 4353
BarsCalculated
........................................................................................................... 4354
GetData ........................................................................................................... 4355
Refresh ........................................................................................................... 4358
Minimum ........................................................................................................... 4359
MinValue ........................................................................................................... 4360
Maximum ........................................................................................................... 4361
MaxValue ........................................................................................................... 4362
MethodDescription
........................................................................................................... 4363
PriceDescription
........................................................................................................... 4364
VolumeDescription
........................................................................................................... 4365
AddToChart
........................................................................................................... 4366
DeleteFromChart
........................................................................................................... 4367
CI ndicators
................................................................................................................ 4368
Create ........................................................................................................... 4369
Refresh ........................................................................................................... 4370
Timeseries
.........................................................................................................................
classes 4371
CiSpread ................................................................................................................ 4372
Create ........................................................................................................... 4374
e z
BufferResi ........................................................................................................... 4375
GetData ........................................................................................................... 4376
Refresh ........................................................................................................... 4378
CiTime ................................................................................................................ 4379
Create ........................................................................................................... 4381
e z
BufferResi ........................................................................................................... 4382
GetData ........................................................................................................... 4383
Refresh ........................................................................................................... 4385
CiTickVolume
................................................................................................................ 4386
Create ........................................................................................................... 4388
e z
BufferResi ........................................................................................................... 4389
GetData ........................................................................................................... 4390
Refresh ........................................................................................................... 4392
CiRealVolume
................................................................................................................ 4393
Create ........................................................................................................... 4395
e z
BufferResi ........................................................................................................... 4396
GetData ........................................................................................................... 4397
Refresh ........................................................................................................... 4399
CiOpen ................................................................................................................ 4400
Create ........................................................................................................... 4402
GetData ........................................................................................................... 4403
CiHigh ................................................................................................................ 4405

© 2000-2021, MetaQuotes Ltd


46 Content

Create ........................................................................................................... 4407


GetData ........................................................................................................... 4408
CiLow ................................................................................................................ 4410
Create ........................................................................................................... 4412
GetData ........................................................................................................... 4413
CiClose ................................................................................................................ 4415
Create ........................................................................................................... 4417
GetData ........................................................................................................... 4418
Trend I ndicators
......................................................................................................................... 4420
CiAD X ................................................................................................................ 4421
MaPeriod ........................................................................................................... 4423
Create ........................................................................................................... 4424
Main ........................................................................................................... 4425
Plus ........................................................................................................... 4426
Minus ........................................................................................................... 4427
Type ........................................................................................................... 4428
X
CiAD Wilder
................................................................................................................ 4429
MaPeriod ........................................................................................................... 4431
Create ........................................................................................................... 4432
Main ........................................................................................................... 4433
Plus ........................................................................................................... 4434
Minus ........................................................................................................... 4435
Type ........................................................................................................... 4436
CiBands ................................................................................................................ 4437
MaPeriod ........................................................................................................... 4439
MaShift ........................................................................................................... 4440
Deviation ........................................................................................................... 4441
Applied ........................................................................................................... 4442
Create ........................................................................................................... 4443
Base ........................................................................................................... 4444
Upper ........................................................................................................... 4445
Lower ........................................................................................................... 4446
Type ........................................................................................................... 4447
CiEnvelopes
................................................................................................................ 4448
MaPeriod ........................................................................................................... 4450
MaShift ........................................................................................................... 4451
MaMethod ........................................................................................................... 4452
Deviation ........................................................................................................... 4453
Applied ........................................................................................................... 4454
Create ........................................................................................................... 4455
Upper ........................................................................................................... 4456
Lower ........................................................................................................... 4457
Type ........................................................................................................... 4458
CiI chimoku................................................................................................................ 4459
TenkanSenPeriod
........................................................................................................... 4461
KijunSenPeriod
........................................................................................................... 4462
SenkouSpanBPeriod
........................................................................................................... 4463
Create ........................................................................................................... 4464
TenkanSen........................................................................................................... 4465
KijunSen ........................................................................................................... 4466
SenkouSpanA
........................................................................................................... 4467
SenkouSpanB
........................................................................................................... 4468
ChinkouSpan
........................................................................................................... 4469
Type ........................................................................................................... 4470
CiMA ................................................................................................................ 4471
MaPeriod ........................................................................................................... 4473
MaShift ........................................................................................................... 4474
MaMethod ........................................................................................................... 4475

© 2000-2021, MetaQuotes Ltd


47 Content

Applied ........................................................................................................... 4476


Create ........................................................................................................... 4477
Main ........................................................................................................... 4478
Type ........................................................................................................... 4479
CiSAR ................................................................................................................ 4480
SarStep ........................................................................................................... 4482
Maximum ........................................................................................................... 4483
Create ........................................................................................................... 4484
Main ........................................................................................................... 4485
Type ........................................................................................................... 4486
CiStdDev ................................................................................................................ 4487
MaPeriod ........................................................................................................... 4489
MaShift ........................................................................................................... 4490
MaMethod ........................................................................................................... 4491
Applied ........................................................................................................... 4492
Create ........................................................................................................... 4493
Main ........................................................................................................... 4494
Type ........................................................................................................... 4495
CiDEMA ................................................................................................................ 4496
MaPeriod ........................................................................................................... 4498
I ndShift ........................................................................................................... 4499
Applied ........................................................................................................... 4500
Create ........................................................................................................... 4501
Main ........................................................................................................... 4502
Type ........................................................................................................... 4503
CiTEMA ................................................................................................................ 4504
MaPeriod ........................................................................................................... 4506
I ndShift ........................................................................................................... 4507
Applied ........................................................................................................... 4508
Create ........................................................................................................... 4509
Main ........................................................................................................... 4510
Type ........................................................................................................... 4511
CiFrAMA ................................................................................................................ 4512
MaPeriod ........................................................................................................... 4514
I ndShift ........................................................................................................... 4515
Applied ........................................................................................................... 4516
Create ........................................................................................................... 4517
Main ........................................................................................................... 4518
Type ........................................................................................................... 4519
CiAMA ................................................................................................................ 4520
MaPeriod ........................................................................................................... 4522
FastEmaPeriod
........................................................................................................... 4523
SlowEmaPeriod
........................................................................................................... 4524
I ndShift ........................................................................................................... 4525
Applied ........................................................................................................... 4526
Create ........................................................................................................... 4527
Main ........................................................................................................... 4528
Type ........................................................................................................... 4529
CiVI DyA ................................................................................................................ 4530
CmoPeriod........................................................................................................... 4532
EmaPeriod ........................................................................................................... 4533
I ndShift ........................................................................................................... 4534
Applied ........................................................................................................... 4535
Create ........................................................................................................... 4536
Main ........................................................................................................... 4537
Type ........................................................................................................... 4538
Oscillators
......................................................................................................................... 4539
CiATR ................................................................................................................ 4540

© 2000-2021, MetaQuotes Ltd


48 Content

MaPeriod ........................................................................................................... 4542


Create ........................................................................................................... 4543
Main ........................................................................................................... 4544
Type ........................................................................................................... 4545
CiBearsPower
................................................................................................................ 4546
MaPeriod ........................................................................................................... 4548
Create ........................................................................................................... 4549
Main ........................................................................................................... 4550
Type ........................................................................................................... 4551
CiBullsPower
................................................................................................................ 4552
MaPeriod ........................................................................................................... 4554
Create ........................................................................................................... 4555
Main ........................................................................................................... 4556
Type ........................................................................................................... 4557
CiCCI ................................................................................................................ 4558
MaPeriod ........................................................................................................... 4560
Applied ........................................................................................................... 4561
Create ........................................................................................................... 4562
Main ........................................................................................................... 4563
Type ........................................................................................................... 4564
CiChaikin ................................................................................................................ 4565
FastMaPeriod
........................................................................................................... 4567
SlowMaPeriod
........................................................................................................... 4568
MaMethod ........................................................................................................... 4569
Applied ........................................................................................................... 4570
Create ........................................................................................................... 4571
Main ........................................................................................................... 4572
Type ........................................................................................................... 4573
CiDeMarker
................................................................................................................ 4574
MaPeriod ........................................................................................................... 4576
Create ........................................................................................................... 4577
Main ........................................................................................................... 4578
Type ........................................................................................................... 4579
CiForce ................................................................................................................ 4580
MaPeriod ........................................................................................................... 4582
MaMethod ........................................................................................................... 4583
Applied ........................................................................................................... 4584
Create ........................................................................................................... 4585
Main ........................................................................................................... 4586
Type ........................................................................................................... 4587
CiMACD ................................................................................................................ 4588
FastEmaPeriod
........................................................................................................... 4590
SlowEmaPeriod
........................................................................................................... 4591
SignalPeriod
........................................................................................................... 4592
Applied ........................................................................................................... 4593
Create ........................................................................................................... 4594
Main ........................................................................................................... 4595
Signal ........................................................................................................... 4596
Type ........................................................................................................... 4597
CiMomentum
................................................................................................................ 4598
MaPeriod ........................................................................................................... 4600
Applied ........................................................................................................... 4601
Create ........................................................................................................... 4602
Main ........................................................................................................... 4603
Type ........................................................................................................... 4604
CiOsMA ................................................................................................................ 4605
FastEmaPeriod
........................................................................................................... 4607
SlowEmaPeriod
........................................................................................................... 4608

© 2000-2021, MetaQuotes Ltd


49 Content

SignalPeriod
........................................................................................................... 4609
Applied ........................................................................................................... 4610
Create ........................................................................................................... 4611
Main ........................................................................................................... 4612
Type ........................................................................................................... 4613
CiRSI ................................................................................................................ 4614
MaPeriod ........................................................................................................... 4616
Applied ........................................................................................................... 4617
Create ........................................................................................................... 4618
Main ........................................................................................................... 4619
Type ........................................................................................................... 4620
CiRVI ................................................................................................................ 4621
MaPeriod ........................................................................................................... 4623
Create ........................................................................................................... 4624
Main ........................................................................................................... 4625
Signal ........................................................................................................... 4626
Type ........................................................................................................... 4627
CiStochastic
................................................................................................................ 4628
Kperiod ........................................................................................................... 4630
Dperiod ........................................................................................................... 4631
Slowing ........................................................................................................... 4632
MaMethod ........................................................................................................... 4633
PriceField ........................................................................................................... 4634
Create ........................................................................................................... 4635
Main ........................................................................................................... 4636
Signal ........................................................................................................... 4637
Type ........................................................................................................... 4638
CiTri X ................................................................................................................ 4639
MaPeriod ........................................................................................................... 4641
Applied ........................................................................................................... 4642
Create ........................................................................................................... 4643
Main ........................................................................................................... 4644
Type ........................................................................................................... 4645
CiWPR ................................................................................................................ 4646
CalcPeriod........................................................................................................... 4648
Create ........................................................................................................... 4649
Main ........................................................................................................... 4650
Type ........................................................................................................... 4651
Volume .........................................................................................................................
I ndicators 4652
CiAD ................................................................................................................ 4653
Applied ........................................................................................................... 4655
Create ........................................................................................................... 4656
Main ........................................................................................................... 4657
Type ........................................................................................................... 4658
CiMFI ................................................................................................................ 4659
MaPeriod ........................................................................................................... 4661
Applied ........................................................................................................... 4662
Create ........................................................................................................... 4663
Main ........................................................................................................... 4664
Type ........................................................................................................... 4665
CiOBV ................................................................................................................ 4666
Applied ........................................................................................................... 4668
Create ........................................................................................................... 4669
Main ........................................................................................................... 4670
Type ........................................................................................................... 4671
CiVolumes ................................................................................................................ 4672
Applied ........................................................................................................... 4674
Create ........................................................................................................... 4675

© 2000-2021, MetaQuotes Ltd


50 Content

Main ........................................................................................................... 4676


Type ........................................................................................................... 4677
Bill Williams
.........................................................................................................................
I ndicators 4678
CiAC ................................................................................................................ 4679
Create ........................................................................................................... 4681
Main ........................................................................................................... 4682
Type ........................................................................................................... 4683
CiAlligator ................................................................................................................ 4684
JawPeriod ........................................................................................................... 4686
JawShift ........................................................................................................... 4687
TeethPeriod
........................................................................................................... 4688
TeethShift ........................................................................................................... 4689
LipsPeriod ........................................................................................................... 4690
LipsShift ........................................................................................................... 4691
MaMethod ........................................................................................................... 4692
Applied ........................................................................................................... 4693
Create ........................................................................................................... 4694
Jaw ........................................................................................................... 4695
Teeth ........................................................................................................... 4696
Lips ........................................................................................................... 4697
Type ........................................................................................................... 4698
CiAO ................................................................................................................ 4699
Create ........................................................................................................... 4701
Main ........................................................................................................... 4702
Type ........................................................................................................... 4703
CiFractals ................................................................................................................ 4704
Create ........................................................................................................... 4706
Upper ........................................................................................................... 4707
Lower ........................................................................................................... 4708
Type ........................................................................................................... 4709
G
Ci ator ................................................................................................................ 4710
JawPeriod ........................................................................................................... 4712
JawShift ........................................................................................................... 4713
TeethPeriod
........................................................................................................... 4714
TeethShift ........................................................................................................... 4715
LipsPeriod ........................................................................................................... 4716
LipsShift ........................................................................................................... 4717
MaMethod ........................................................................................................... 4718
Applied ........................................................................................................... 4719
Create ........................................................................................................... 4720
Upper ........................................................................................................... 4721
Lower ........................................................................................................... 4722
Type ........................................................................................................... 4723
CiBWMFI ................................................................................................................ 4724
Applied ........................................................................................................... 4726
Create ........................................................................................................... 4727
Main ........................................................................................................... 4728
Type ........................................................................................................... 4729
Custom.........................................................................................................................
indicators 4730
NumBuffers................................................................................................................ 4731
NumParams................................................................................................................ 4732
ParamType................................................................................................................ 4733
ParamLong................................................................................................................ 4734
ParamDouble
................................................................................................................ 4735
ParamString
................................................................................................................ 4736
Type ................................................................................................................ 4737
............................................................................................................................4738
Trade Classes
CAccountI
.........................................................................................................................
nfo 4739

© 2000-2021, MetaQuotes Ltd


51 Content

Login ................................................................................................................ 4741


TradeMode................................................................................................................ 4742
TradeModeDescription
................................................................................................................ 4743
Leverage ................................................................................................................ 4744
StopoutMode
................................................................................................................ 4745
StopoutModeDescription
................................................................................................................ 4746
MarginMode
................................................................................................................ 4747
MarginModeDescription
................................................................................................................ 4748
TradeAllowed
................................................................................................................ 4749
TradeExpert
................................................................................................................ 4750
LimitOrders
................................................................................................................ 4751
Balance ................................................................................................................ 4752
Credit ................................................................................................................ 4753
Profit ................................................................................................................ 4754
q
E uity ................................................................................................................ 4755
Margin ................................................................................................................ 4756
FreeMargin................................................................................................................ 4757
MarginLevel
................................................................................................................ 4758
MarginCall ................................................................................................................ 4759
MarginStopOut
................................................................................................................ 4760
Name ................................................................................................................ 4761
Server ................................................................................................................ 4762
Currency ................................................................................................................ 4763
Company ................................................................................................................ 4764
I nfoI nteger................................................................................................................ 4765
I nfoDouble ................................................................................................................ 4766
I nfoString ................................................................................................................ 4767
OrderProfitCheck
................................................................................................................ 4768
MarginCheck
................................................................................................................ 4769
FreeMarginCheck
................................................................................................................ 4770
MaxLotCheck
................................................................................................................ 4771
CSymbolI
.........................................................................................................................
nfo 4772
Refresh ................................................................................................................ 4777
RefreshRates
................................................................................................................ 4778
Name ................................................................................................................ 4779
Select ................................................................................................................ 4780
I sSynchroni z
................................................................................................................
ed 4781
Volume ................................................................................................................ 4782
VolumeHigh................................................................................................................ 4783
VolumeLow................................................................................................................ 4784
Time ................................................................................................................ 4785
Spread ................................................................................................................ 4786
SpreadFloat
................................................................................................................ 4787
TicksBookDepth
................................................................................................................ 4788
StopsLevel................................................................................................................ 4789
z
Free eLevel
................................................................................................................ 4790
Bid ................................................................................................................ 4791
BidHigh ................................................................................................................ 4792
BidLow ................................................................................................................ 4793
Ask ................................................................................................................ 4794
AskHigh ................................................................................................................ 4795
AskLow ................................................................................................................ 4796
Last ................................................................................................................ 4797
LastHigh ................................................................................................................ 4798
LastLow ................................................................................................................ 4799
TradeCalcMode
................................................................................................................ 4800
TradeCalcModeDescription
................................................................................................................ 4801
TradeMode................................................................................................................ 4802

© 2000-2021, MetaQuotes Ltd


52 Content

TradeModeDescription
................................................................................................................ 4803
TradeExecution
................................................................................................................ 4804
TradeExecutionDescription
................................................................................................................ 4805
SwapMode ................................................................................................................ 4806
SwapModeDescription
................................................................................................................ 4807
SwapRollover3days
................................................................................................................ 4808
SwapRollover3daysDescription
................................................................................................................ 4809
MarginI nitial
................................................................................................................ 4810
MarginMaintenance
................................................................................................................ 4811
MarginLong................................................................................................................ 4812
MarginShort
................................................................................................................ 4813
MarginLimit
................................................................................................................ 4814
MarginStop................................................................................................................ 4815
MarginStopLimit
................................................................................................................ 4816
TradeTimeFlags
................................................................................................................ 4817
TradeFillFlags
................................................................................................................ 4818
Digits ................................................................................................................ 4819
Point ................................................................................................................ 4820
TickValue ................................................................................................................ 4821
TickValueProfit
................................................................................................................ 4822
TickValueLoss
................................................................................................................ 4823
TickSi e z ................................................................................................................ 4824
e z
ContractSi................................................................................................................ 4825
LotsMin ................................................................................................................ 4826
LotsMax ................................................................................................................ 4827
LotsStep ................................................................................................................ 4828
LotsLimit ................................................................................................................ 4829
SwapLong ................................................................................................................ 4830
SwapShort ................................................................................................................ 4831
CurrencyBase
................................................................................................................ 4832
CurrencyProfit
................................................................................................................ 4833
CurrencyMargin
................................................................................................................ 4834
Bank ................................................................................................................ 4835
Description................................................................................................................ 4836
Path ................................................................................................................ 4837
SessionDeals
................................................................................................................ 4838
SessionBuyOrders
................................................................................................................ 4839
SessionSellOrders
................................................................................................................ 4840
SessionTurnover
................................................................................................................ 4841
SessionI nterest
................................................................................................................ 4842
SessionBuyOrdersVolume
................................................................................................................ 4843
SessionSellOrdersVolume
................................................................................................................ 4844
SessionOpen
................................................................................................................ 4845
SessionClose
................................................................................................................ 4846
SessionAW ................................................................................................................ 4847
SessionPriceSettlement
................................................................................................................ 4848
SessionPriceLimitMin
................................................................................................................ 4849
SessionPriceLimitMax
................................................................................................................ 4850
I nfoI nteger................................................................................................................ 4851
I nfoDouble ................................................................................................................ 4852
I nfoString ................................................................................................................ 4853
z
Normali ePrice
................................................................................................................ 4854
COrderI.........................................................................................................................
nfo 4855
Ticket ................................................................................................................ 4857
TimeSetup ................................................................................................................ 4858
TimeSetupMsc
................................................................................................................ 4859
OrderType................................................................................................................ 4860
TypeDescription
................................................................................................................ 4861

© 2000-2021, MetaQuotes Ltd


53 Content

State ................................................................................................................ 4862


StateDescription
................................................................................................................ 4863
TimeExpiration
................................................................................................................ 4864
TimeDone ................................................................................................................ 4865
TimeDoneMsc
................................................................................................................ 4866
TypeFilling ................................................................................................................ 4867
TypeFillingDescription
................................................................................................................ 4868
TypeTime ................................................................................................................ 4869
TypeTimeDescription
................................................................................................................ 4870
Magic ................................................................................................................ 4871
PositionI d ................................................................................................................ 4872
VolumeI nitial
................................................................................................................ 4873
VolumeCurrent
................................................................................................................ 4874
PriceOpen ................................................................................................................ 4875
StopLoss ................................................................................................................ 4876
TakeProfit ................................................................................................................ 4877
PriceCurrent
................................................................................................................ 4878
PriceStopLimit
................................................................................................................ 4879
Symbol ................................................................................................................ 4880
Comment ................................................................................................................ 4881
I nfoI nteger................................................................................................................ 4882
I nfoDouble ................................................................................................................ 4883
I nfoString ................................................................................................................ 4884
StoreState................................................................................................................ 4885
CheckState................................................................................................................ 4886
Select ................................................................................................................ 4887
SelectByI ndex
................................................................................................................ 4888
CHistoryOrderI
.........................................................................................................................
nfo 4889
TimeSetup ................................................................................................................ 4891
TimeSetupMsc
................................................................................................................ 4892
OrderType................................................................................................................ 4893
TypeDescription
................................................................................................................ 4894
State ................................................................................................................ 4895
StateDescription
................................................................................................................ 4896
TimeExpiration
................................................................................................................ 4897
TimeDone ................................................................................................................ 4898
TimeDoneMsc
................................................................................................................ 4899
TypeFilling ................................................................................................................ 4900
TypeFillingDescription
................................................................................................................ 4901
TypeTime ................................................................................................................ 4902
TypeTimeDescription
................................................................................................................ 4903
Magic ................................................................................................................ 4904
PositionI d ................................................................................................................ 4905
VolumeI nitial
................................................................................................................ 4906
VolumeCurrent
................................................................................................................ 4907
PriceOpen ................................................................................................................ 4908
StopLoss ................................................................................................................ 4909
TakeProfit ................................................................................................................ 4910
PriceCurrent
................................................................................................................ 4911
PriceStopLimit
................................................................................................................ 4912
Symbol ................................................................................................................ 4913
Comment ................................................................................................................ 4914
I nfoI nteger................................................................................................................ 4915
I nfoDouble ................................................................................................................ 4916
I nfoString ................................................................................................................ 4917
Ticket ................................................................................................................ 4918
SelectByI ndex
................................................................................................................ 4919
CPositionI
.........................................................................................................................
nfo 4920

© 2000-2021, MetaQuotes Ltd


54 Content

Time ................................................................................................................ 4922


TimeMsc ................................................................................................................ 4923
TimeUpdate
................................................................................................................ 4924
TimeUpdateMsc
................................................................................................................ 4925
PositionType
................................................................................................................ 4926
TypeDescription
................................................................................................................ 4927
Magic ................................................................................................................ 4928
I dentifier ................................................................................................................ 4929
Volume ................................................................................................................ 4930
PriceOpen ................................................................................................................ 4931
StopLoss ................................................................................................................ 4932
TakeProfit ................................................................................................................ 4933
PriceCurrent
................................................................................................................ 4934
Commission................................................................................................................ 4935
Swap ................................................................................................................ 4936
Profit ................................................................................................................ 4937
Symbol ................................................................................................................ 4938
Comment ................................................................................................................ 4939
I nfoI nteger................................................................................................................ 4940
I nfoDouble ................................................................................................................ 4941
I nfoString ................................................................................................................ 4942
Select ................................................................................................................ 4943
SelectByI ndex
................................................................................................................ 4944
SelectByMagic
................................................................................................................ 4945
SelectByTicket
................................................................................................................ 4946
StoreState................................................................................................................ 4947
CheckState................................................................................................................ 4948
CDealI nfo
......................................................................................................................... 4949
Order ................................................................................................................ 4951
Time ................................................................................................................ 4952
TimeMsc ................................................................................................................ 4953
DealType ................................................................................................................ 4954
TypeDescription
................................................................................................................ 4955
Entry ................................................................................................................ 4956
EntryDescription
................................................................................................................ 4957
Magic ................................................................................................................ 4958
PositionI d ................................................................................................................ 4959
Volume ................................................................................................................ 4960
Price ................................................................................................................ 4961
Commision ................................................................................................................ 4962
Swap ................................................................................................................ 4963
Profit ................................................................................................................ 4964
Symbol ................................................................................................................ 4965
Comment ................................................................................................................ 4966
I nfoI nteger................................................................................................................ 4967
I nfoDouble ................................................................................................................ 4968
I nfoString ................................................................................................................ 4969
Ticket ................................................................................................................ 4970
SelectByI ndex
................................................................................................................ 4971
CTrade ......................................................................................................................... 4972
LogLevel ................................................................................................................ 4977
SetExpertMagicNumber
................................................................................................................ 4978
SetDeviationI
................................................................................................................
nPoints 4979
SetTypeFilling
................................................................................................................ 4980
SetTypeFillingBySymbol
................................................................................................................ 4981
SetAsyncMode
................................................................................................................ 4982
SetMarginMode
................................................................................................................ 4983
OrderOpen................................................................................................................ 4984

© 2000-2021, MetaQuotes Ltd


55 Content

OrderModify
................................................................................................................ 4986
OrderDelete
................................................................................................................ 4987
PositionOpen
................................................................................................................ 4988
PositionModify
................................................................................................................ 4989
PositionClose
................................................................................................................ 4990
PositionClosePartial
................................................................................................................ 4991
PositionCloseBy
................................................................................................................ 4993
Buy ................................................................................................................ 4994
Sell ................................................................................................................ 4995
BuyLimit ................................................................................................................ 4996
BuyStop ................................................................................................................ 4997
SellLimit ................................................................................................................ 4998
SellStop ................................................................................................................ 4999
q
Re uest ................................................................................................................ 5000
RequestAction
................................................................................................................ 5001
RequestActionDescription
................................................................................................................ 5002
RequestMagic
................................................................................................................ 5003
RequestOrder
................................................................................................................ 5004
RequestSymbol
................................................................................................................ 5005
RequestVolume
................................................................................................................ 5006
RequestPrice
................................................................................................................ 5007
RequestStopLimit
................................................................................................................ 5008
RequestSL ................................................................................................................ 5009
RequestTP ................................................................................................................ 5010
RequestDeviation
................................................................................................................ 5011
RequestType
................................................................................................................ 5012
RequestTypeDescription
................................................................................................................ 5013
RequestTypeFilling
................................................................................................................ 5014
RequestTypeFillingDescription
................................................................................................................ 5015
RequestTypeTime
................................................................................................................ 5016
RequestTypeTimeDescription
................................................................................................................ 5017
RequestExpiration
................................................................................................................ 5018
RequestComment
................................................................................................................ 5019
RequestPosition
................................................................................................................ 5020
RequestPositionBy
................................................................................................................ 5021
Result ................................................................................................................ 5022
ResultRetcode
................................................................................................................ 5023
ResultRetcodeDescription
................................................................................................................ 5024
ResultDeal ................................................................................................................ 5025
ResultOrder
................................................................................................................ 5026
ResultVolume
................................................................................................................ 5027
ResultPrice................................................................................................................ 5028
ResultBid ................................................................................................................ 5029
ResultAsk ................................................................................................................ 5030
ResultComment
................................................................................................................ 5031
CheckResult
................................................................................................................ 5032
CheckResultRetcode
................................................................................................................ 5033
CheckResultRetcodeDescription
................................................................................................................ 5034
CheckResultBalance
................................................................................................................ 5035
CheckResultE q
................................................................................................................
uity 5036
CheckResultProfit
................................................................................................................ 5037
CheckResultMargin
................................................................................................................ 5038
CheckResultMarginFree
................................................................................................................ 5039
CheckResultMarginLevel
................................................................................................................ 5040
CheckResultComment
................................................................................................................ 5041
q
PrintRe uest
................................................................................................................ 5042
PrintResult................................................................................................................ 5043
FormatRe uestq
................................................................................................................ 5044

© 2000-2021, MetaQuotes Ltd


56 Content

q
FormatRe uestResult
................................................................................................................ 5045
CTerminalI
.........................................................................................................................
nfo 5046
Build ................................................................................................................ 5048
I sConnected
................................................................................................................ 5049
I sDLLsAllowed
................................................................................................................ 5050
I sTradeAllowed
................................................................................................................ 5051
I sEmailEnabled
................................................................................................................ 5052
I sFtpEnabled
................................................................................................................ 5053
MaxBars ................................................................................................................ 5054
CodePage ................................................................................................................ 5055
CPUCores ................................................................................................................ 5056
MemoryPhysical
................................................................................................................ 5057
MemoryTotal
................................................................................................................ 5058
MemoryAvailable
................................................................................................................ 5059
MemoryUsed
................................................................................................................ 5060
X
I s 64 ................................................................................................................ 5061
OpenCLSupport
................................................................................................................ 5062
DiskSpace ................................................................................................................ 5063
Language ................................................................................................................ 5064
Name ................................................................................................................ 5065
Company ................................................................................................................ 5066
Path ................................................................................................................ 5067
DataPath ................................................................................................................ 5068
CommonDataPath
................................................................................................................ 5069
I nfoI nteger................................................................................................................ 5070
I nfoString ................................................................................................................ 5071
............................................................................................................................5072
Strategy Modules
Base classes
.........................................................................................................................
for Expert Advisors 5075
CExpertBase
................................................................................................................ 5076
I nitPhase ........................................................................................................... 5079
TrendType........................................................................................................... 5080
UsedSeries........................................................................................................... 5081
EveryTick ........................................................................................................... 5082
Open ........................................................................................................... 5083
High ........................................................................................................... 5084
Low ........................................................................................................... 5085
Close ........................................................................................................... 5086
Spread ........................................................................................................... 5087
Time ........................................................................................................... 5088
TickVolume........................................................................................................... 5089
RealVolume........................................................................................................... 5090
I nit ........................................................................................................... 5091
Symbol ........................................................................................................... 5092
Period ........................................................................................................... 5093
Magic ........................................................................................................... 5094
ValidationSettings
........................................................................................................... 5095
SetPriceSeries
........................................................................................................... 5096
SetOtherSeries
........................................................................................................... 5097
I nitI ndicators
........................................................................................................... 5098
I nitOpen ........................................................................................................... 5099
I nitHigh ........................................................................................................... 5100
I nitLow ........................................................................................................... 5101
I nitClose ........................................................................................................... 5102
I nitSpread ........................................................................................................... 5103
I nitTime ........................................................................................................... 5104
I nitTickVolume
........................................................................................................... 5105
I nitRealVolume
........................................................................................................... 5106
PriceLevelUnit
........................................................................................................... 5107

© 2000-2021, MetaQuotes Ltd


57 Content

StartI ndex........................................................................................................... 5108


CompareMagic
........................................................................................................... 5109
CExpert ................................................................................................................ 5110
I nit ........................................................................................................... 5115
Magic ........................................................................................................... 5116
I nitSignal ........................................................................................................... 5117
I nitTrailing........................................................................................................... 5118
I nitMoney ........................................................................................................... 5119
I nitTrade ........................................................................................................... 5120
Deinit ........................................................................................................... 5121
OnTickProcess
........................................................................................................... 5122
OnTradeProcess
........................................................................................................... 5123
OnTimerProcess
........................................................................................................... 5124
OnChartEventProcess
........................................................................................................... 5125
OnBookEventProcess
........................................................................................................... 5126
MaxOrders........................................................................................................... 5127
Signal ........................................................................................................... 5128
ValidationSettings
........................................................................................................... 5129
I nitI ndicators
........................................................................................................... 5130
OnTick ........................................................................................................... 5131
OnTrade ........................................................................................................... 5132
OnTimer ........................................................................................................... 5133
OnChartEvent
........................................................................................................... 5134
OnBookEvent
........................................................................................................... 5135
I nitParameters
........................................................................................................... 5136
DeinitTrade
........................................................................................................... 5137
DeinitSignal
........................................................................................................... 5138
DeinitTrailing
........................................................................................................... 5139
DeinitMoney
........................................................................................................... 5140
DeinitI ndicators
........................................................................................................... 5141
Refresh ........................................................................................................... 5142
Processing........................................................................................................... 5143
SelectPosition
........................................................................................................... 5145
CheckOpen........................................................................................................... 5146
CheckOpenLong
........................................................................................................... 5147
CheckOpenShort
........................................................................................................... 5148
OpenLong ........................................................................................................... 5149
OpenShort ........................................................................................................... 5150
CheckReverse
........................................................................................................... 5151
CheckReverseLong
........................................................................................................... 5152
CheckReverseShort
........................................................................................................... 5153
ReverseLong
........................................................................................................... 5154
ReverseShort
........................................................................................................... 5156
CheckClose........................................................................................................... 5158
CheckCloseLong
........................................................................................................... 5159
CheckCloseShort
........................................................................................................... 5160
CloseAll ........................................................................................................... 5161
Close ........................................................................................................... 5162
CloseLong ........................................................................................................... 5163
CloseShort ........................................................................................................... 5164
CheckTrailingStop
........................................................................................................... 5165
CheckTrailingStopLong
........................................................................................................... 5166
CheckTrailingStopShort
........................................................................................................... 5167
TrailingStopLong
........................................................................................................... 5168
TrailingStopShort
........................................................................................................... 5169
CheckTrailingOrderLong
........................................................................................................... 5170
CheckTrailingOrderShort
........................................................................................................... 5171
TrailingOrderLong
........................................................................................................... 5172

© 2000-2021, MetaQuotes Ltd


58 Content

TrailingOrderShort
........................................................................................................... 5173
CheckDeleteOrderLong
........................................................................................................... 5174
CheckDeleteOrderShort
........................................................................................................... 5175
DeleteOrders
........................................................................................................... 5176
DeleteOrder
........................................................................................................... 5177
DeleteOrderLong
........................................................................................................... 5178
DeleteOrderShort
........................................................................................................... 5179
LotOpenLong
........................................................................................................... 5180
LotOpenShort
........................................................................................................... 5181
LotReverse........................................................................................................... 5182
PrepareHistoryDate
........................................................................................................... 5183
HistoryPoint
........................................................................................................... 5184
CheckTradeState
........................................................................................................... 5185
WaitEvent ........................................................................................................... 5186
NoWaitEvent
........................................................................................................... 5187
TradeEventPositionStopTake
........................................................................................................... 5188
TradeEventOrderTriggered
........................................................................................................... 5189
TradeEventPositionOpened
........................................................................................................... 5190
TradeEventPositionVolumeChanged
........................................................................................................... 5191
TradeEventPositionModified
........................................................................................................... 5192
TradeEventPositionClosed
........................................................................................................... 5193
TradeEventOrderPlaced
........................................................................................................... 5194
TradeEventOrderModified
........................................................................................................... 5195
TradeEventOrderDeleted
........................................................................................................... 5196
TradeEventNotI
...........................................................................................................
dentified 5197
TimeframeAdd
........................................................................................................... 5198
TimeframesFlags
........................................................................................................... 5199
CExpertSignal
................................................................................................................ 5200
BasePrice ........................................................................................................... 5203
UsedSeries........................................................................................................... 5204
Weight ........................................................................................................... 5205
PatternsUsage
........................................................................................................... 5206
General ........................................................................................................... 5207
I gnore ........................................................................................................... 5208
I nvert ........................................................................................................... 5209
ThresholdOpen
........................................................................................................... 5210
ThresholdClose
........................................................................................................... 5211
PriceLevel........................................................................................................... 5212
StopLevel ........................................................................................................... 5213
TakeLevel ........................................................................................................... 5214
Expiration ........................................................................................................... 5215
Magic ........................................................................................................... 5216
ValidationSettings
........................................................................................................... 5217
I nitI ndicators
........................................................................................................... 5218
AddFilter ........................................................................................................... 5219
CheckOpenLong
........................................................................................................... 5220
CheckOpenShort
........................................................................................................... 5221
OpenLongParams
........................................................................................................... 5222
OpenShortParams
........................................................................................................... 5223
CheckCloseLong
........................................................................................................... 5224
CheckCloseShort
........................................................................................................... 5225
CloseLongParams
........................................................................................................... 5226
CloseShortParams
........................................................................................................... 5227
CheckReverseLong
........................................................................................................... 5228
CheckReverseShort
........................................................................................................... 5229
CheckTrailingOrderLong
........................................................................................................... 5230
CheckTrailingOrderShort
........................................................................................................... 5231
LongCondition
........................................................................................................... 5232

© 2000-2021, MetaQuotes Ltd


59 Content

ShortCondition
........................................................................................................... 5233
Direction ........................................................................................................... 5234
CExpertTrailing
................................................................................................................ 5235
CheckTrailingStopLong
........................................................................................................... 5237
CheckTrailingStopShort
........................................................................................................... 5238
CExpertMoney
................................................................................................................ 5239
Percent ........................................................................................................... 5240
ValidationSettings
........................................................................................................... 5241
CheckOpenLong
........................................................................................................... 5242
CheckOpenShort
........................................................................................................... 5243
CheckReverse
........................................................................................................... 5244
CheckClose........................................................................................................... 5245
Modules.........................................................................................................................
of Trade Signals 5246
Signals of the
................................................................................................................
I ndicator Accelerator Oscillator 5249
Signals of the
................................................................................................................
I ndicator Adaptive Moving Average 5252
Signals of the
................................................................................................................
I ndicator Awesome Oscillator 5256
Signals of the
................................................................................................................
Oscillator Bears Power 5260
Signals of the
................................................................................................................
Oscillator Bulls Power 5262
Signals of the
................................................................................................................
Oscillator Commodity Channel I ndex 5264
Signals of the
................................................................................................................
Oscillator DeMarker 5268
Signals of the
................................................................................................................
I ndicator Double Exponential Moving Average 5272
Signals of the
................................................................................................................
I ndicator Envelopes 5276
Signals of the
................................................................................................................
I ndicator Fractal Adaptive Moving Average 5279
Signals of the
................................................................................................................
I ntraday Time Filter 5283
Signals of the
................................................................................................................
Oscillator MACD 5285
Signals of the
................................................................................................................
I ndicator Moving Average 5291
Signals of the
................................................................................................................
I ndicator Parabolic SAR 5295
Signals of the
................................................................................................................
Oscillator Relative Strength I ndex 5297
Signals of the
................................................................................................................
Oscillator Relative Vigor I ndex 5303
Signals of the
................................................................................................................
Oscillator Stochastic 5305
Signals of the
................................................................................................................
Oscillator Triple Exponential Average 5310
Signals of the
................................................................................................................
I ndicator Triple Exponential Moving Average 5314
Signals of the
................................................................................................................
Oscillator Williams Percent Range 5318
Trailing .........................................................................................................................
Stop Classes 5321
CTrailingFixedPips
................................................................................................................ 5322
StopLevel ........................................................................................................... 5324
ProfitLevel........................................................................................................... 5325
ValidationSettings
........................................................................................................... 5326
CheckTrailingStopLong
........................................................................................................... 5327
CheckTrailingStopShort
........................................................................................................... 5328
CTrailingMA
................................................................................................................ 5329
Period ........................................................................................................... 5331
Shift ........................................................................................................... 5332
Method ........................................................................................................... 5333
Applied ........................................................................................................... 5334
I nitI ndicators
........................................................................................................... 5335
ValidationSettings
........................................................................................................... 5336
CheckTrailingStopLong
........................................................................................................... 5337
CheckTrailingStopShort
........................................................................................................... 5338
CTrailingNone
................................................................................................................ 5339
CheckTrailingStopLong
........................................................................................................... 5340
CheckTrailingStopShort
........................................................................................................... 5341
CTrailingPSAR
................................................................................................................ 5342
Step ........................................................................................................... 5344
Maximum ........................................................................................................... 5345
I nitI ndicators
........................................................................................................... 5346
CheckTrailingStopLong
........................................................................................................... 5347
CheckTrailingStopShort
........................................................................................................... 5348

© 2000-2021, MetaQuotes Ltd


60 Content

Money Management
.........................................................................................................................
Classes 5349
CMoneyFixedLot
................................................................................................................ 5350
Lots ........................................................................................................... 5351
ValidationSettings
........................................................................................................... 5352
CheckOpenLong
........................................................................................................... 5353
CheckOpenShort
........................................................................................................... 5354
CMoneyFixedMargin
................................................................................................................ 5355
CheckOpenLong
........................................................................................................... 5356
CheckOpenShort
........................................................................................................... 5357
CMoneyFixedRisk
................................................................................................................ 5358
CheckOpenLong
........................................................................................................... 5359
CheckOpenShort
........................................................................................................... 5360
CMoneyNone
................................................................................................................ 5361
ValidationSettings
........................................................................................................... 5362
CheckOpenLong
........................................................................................................... 5363
CheckOpenShort
........................................................................................................... 5364
z
CMoneySi eOptimi z
................................................................................................................
ed 5365
DecreaseFactor
........................................................................................................... 5366
ValidationSettings
........................................................................................................... 5367
CheckOpenLong
........................................................................................................... 5368
CheckOpenShort
........................................................................................................... 5369
Panels and............................................................................................................................5370
Dialogs
CRect ......................................................................................................................... 5372
Left ................................................................................................................ 5373
Top ................................................................................................................ 5374
Right ................................................................................................................ 5375
Bottom ................................................................................................................ 5376
Width ................................................................................................................ 5377
Height ................................................................................................................ 5378
SetBound ................................................................................................................ 5379
Move ................................................................................................................ 5380
Shift ................................................................................................................ 5381
Contains ................................................................................................................ 5382
Format ................................................................................................................ 5383
CDateTime
......................................................................................................................... 5384
MonthName................................................................................................................ 5386
ShortMonthName
................................................................................................................ 5387
DayName ................................................................................................................ 5388
ShortDayName
................................................................................................................ 5389
DaysI nMonth
................................................................................................................ 5390
DateTime ................................................................................................................ 5391
Date ................................................................................................................ 5392
Time ................................................................................................................ 5393
Sec ................................................................................................................ 5394
Min ................................................................................................................ 5395
Hour ................................................................................................................ 5396
Day ................................................................................................................ 5397
Mon ................................................................................................................ 5398
Y ear ................................................................................................................ 5399
SecDec ................................................................................................................ 5400
SecI nc ................................................................................................................ 5401
MinDec ................................................................................................................ 5402
MinI nc ................................................................................................................ 5403
HourDec ................................................................................................................ 5404
HourI nc ................................................................................................................ 5405
DayDec ................................................................................................................ 5406
DayI nc ................................................................................................................ 5407
MonDec ................................................................................................................ 5408

© 2000-2021, MetaQuotes Ltd


61 Content

MonI nc ................................................................................................................ 5409


Y earDec ................................................................................................................ 5410
Y earI nc ................................................................................................................ 5411
CWnd ......................................................................................................................... 5412
Create ................................................................................................................ 5416
Destroy ................................................................................................................ 5417
OnEvent ................................................................................................................ 5418
OnMouseEvent
................................................................................................................ 5419
Name ................................................................................................................ 5420
ControlsTotal
................................................................................................................ 5421
Control ................................................................................................................ 5422
ControlFind
................................................................................................................ 5423
Rect ................................................................................................................ 5424
Left ................................................................................................................ 5425
Top ................................................................................................................ 5426
Right ................................................................................................................ 5427
Bottom ................................................................................................................ 5428
Width ................................................................................................................ 5429
Height ................................................................................................................ 5430
Move ................................................................................................................ 5431
Shift ................................................................................................................ 5432
Resi ez ................................................................................................................ 5433
Contains ................................................................................................................ 5434
Alignment ................................................................................................................ 5435
Align ................................................................................................................ 5436
Id ................................................................................................................ 5437
I sEnabled ................................................................................................................ 5438
Enable ................................................................................................................ 5439
Disable ................................................................................................................ 5440
I sVisible ................................................................................................................ 5441
Visible ................................................................................................................ 5442
Show ................................................................................................................ 5443
Hide ................................................................................................................ 5444
I sActive ................................................................................................................ 5445
Activate ................................................................................................................ 5446
Deactivate................................................................................................................ 5447
StateFlags ................................................................................................................ 5448
StateFlagsSet
................................................................................................................ 5449
StateFlagsReset
................................................................................................................ 5450
PropFlags ................................................................................................................ 5451
PropFlagsSet
................................................................................................................ 5452
PropFlagsReset
................................................................................................................ 5453
Mouse X ................................................................................................................ 5454
Mouse Y ................................................................................................................ 5455
MouseFlags................................................................................................................ 5456
MouseFocusKill
................................................................................................................ 5457
OnCreate ................................................................................................................ 5458
OnDestroy ................................................................................................................ 5459
OnMove ................................................................................................................ 5460
z
OnResi e ................................................................................................................ 5461
OnEnable ................................................................................................................ 5462
OnDisable ................................................................................................................ 5463
OnShow ................................................................................................................ 5464
OnHide ................................................................................................................ 5465
OnActivate................................................................................................................ 5466
OnDeactivate
................................................................................................................ 5467
OnClick ................................................................................................................ 5468
OnChange ................................................................................................................ 5469

© 2000-2021, MetaQuotes Ltd


62 Content

OnMouseDown
................................................................................................................ 5470
OnMouseUp
................................................................................................................ 5471
OnDragStart
................................................................................................................ 5472
OnDragProcess
................................................................................................................ 5473
OnDragEnd................................................................................................................ 5474
DragObjectCreate
................................................................................................................ 5475
DragObjectDestroy
................................................................................................................ 5476
CWndObj
......................................................................................................................... 5477
OnEvent ................................................................................................................ 5479
Text ................................................................................................................ 5480
Color ................................................................................................................ 5481
ColorBackground
................................................................................................................ 5482
ColorBorder
................................................................................................................ 5483
Font ................................................................................................................ 5484
FontSi ez ................................................................................................................ 5485
ZOrder ................................................................................................................ 5486
OnObjectCreate
................................................................................................................ 5487
OnObjectChange
................................................................................................................ 5488
OnObjectDelete
................................................................................................................ 5489
OnObjectDrag
................................................................................................................ 5490
OnSetText ................................................................................................................ 5491
OnSetColor................................................................................................................ 5492
OnSetColorBackground
................................................................................................................ 5493
OnSetFont ................................................................................................................ 5494
OnSetFontSi z
................................................................................................................
e 5495
Z
OnSet Order
................................................................................................................ 5496
OnDestroy ................................................................................................................ 5497
OnChange ................................................................................................................ 5498
CWndContainer
......................................................................................................................... 5499
Destroy ................................................................................................................ 5501
OnEvent ................................................................................................................ 5502
OnMouseEvent
................................................................................................................ 5503
ControlsTotal
................................................................................................................ 5504
Control ................................................................................................................ 5505
ControlFind
................................................................................................................ 5506
Add ................................................................................................................ 5507
Delete ................................................................................................................ 5508
Move ................................................................................................................ 5509
Shift ................................................................................................................ 5510
Id ................................................................................................................ 5511
Enable ................................................................................................................ 5512
Disable ................................................................................................................ 5513
Show ................................................................................................................ 5514
Hide ................................................................................................................ 5515
MouseFocusKill
................................................................................................................ 5516
Save ................................................................................................................ 5517
Load ................................................................................................................ 5518
z
OnResi e ................................................................................................................ 5519
OnActivate................................................................................................................ 5520
OnDeactivate
................................................................................................................ 5521
CLabel ......................................................................................................................... 5522
Create ................................................................................................................ 5527
OnSetText ................................................................................................................ 5528
OnSetColor................................................................................................................ 5529
OnSetFont ................................................................................................................ 5530
OnSetFontSi z
................................................................................................................
e 5531
OnCreate ................................................................................................................ 5532
OnShow ................................................................................................................ 5533

© 2000-2021, MetaQuotes Ltd


63 Content

OnHide ................................................................................................................ 5534


OnMove ................................................................................................................ 5535
CBmpButton
......................................................................................................................... 5536
Create ................................................................................................................ 5543
Border ................................................................................................................ 5544
BmpNames ................................................................................................................ 5545
BmpOffName
................................................................................................................ 5546
BmpOnName
................................................................................................................ 5547
BmpPassiveName
................................................................................................................ 5548
BmpActiveName
................................................................................................................ 5549
Pressed ................................................................................................................ 5550
Locking ................................................................................................................ 5551
Z
OnSet Order
................................................................................................................ 5552
OnCreate ................................................................................................................ 5553
OnShow ................................................................................................................ 5554
OnHide ................................................................................................................ 5555
OnMove ................................................................................................................ 5556
OnChange ................................................................................................................ 5557
OnActivate................................................................................................................ 5558
OnDeactivate
................................................................................................................ 5559
OnMouseDown
................................................................................................................ 5560
OnMouseUp
................................................................................................................ 5561
CButton......................................................................................................................... 5562
Create ................................................................................................................ 5569
Pressed ................................................................................................................ 5570
Locking ................................................................................................................ 5571
OnSetText ................................................................................................................ 5572
OnSetColor................................................................................................................ 5573
OnSetColorBackground
................................................................................................................ 5574
OnSetColorBorder
................................................................................................................ 5575
OnSetFont ................................................................................................................ 5576
OnSetFontSi z
................................................................................................................
e 5577
OnCreate ................................................................................................................ 5578
OnShow ................................................................................................................ 5579
OnHide ................................................................................................................ 5580
OnMove ................................................................................................................ 5581
z
OnResi e ................................................................................................................ 5582
OnMouseDown
................................................................................................................ 5583
OnMouseUp
................................................................................................................ 5584
CEdit ......................................................................................................................... 5585
Create ................................................................................................................ 5590
ReadOnly ................................................................................................................ 5591
TextAlign ................................................................................................................ 5592
OnObjectEndEdit
................................................................................................................ 5593
OnSetText ................................................................................................................ 5594
OnSetColor................................................................................................................ 5595
OnSetColorBackground
................................................................................................................ 5596
OnSetColorBorder
................................................................................................................ 5597
OnSetFont ................................................................................................................ 5598
OnSetFontSi z
................................................................................................................
e 5599
Z
OnSet Order
................................................................................................................ 5600
OnCreate ................................................................................................................ 5601
OnShow ................................................................................................................ 5602
OnHide ................................................................................................................ 5603
OnMove ................................................................................................................ 5604
z
OnResi e ................................................................................................................ 5605
OnChange ................................................................................................................ 5606
OnClick ................................................................................................................ 5607

© 2000-2021, MetaQuotes Ltd


64 Content

CPanel ......................................................................................................................... 5608


Create ................................................................................................................ 5613
BorderType................................................................................................................ 5614
OnSetText ................................................................................................................ 5615
OnSetColorBackground
................................................................................................................ 5616
OnSetColorBorder
................................................................................................................ 5617
OnCreate ................................................................................................................ 5618
OnShow ................................................................................................................ 5619
OnHide ................................................................................................................ 5620
OnMove ................................................................................................................ 5621
z
OnResi e ................................................................................................................ 5622
OnChange ................................................................................................................ 5623
CPicture
......................................................................................................................... 5624
Create ................................................................................................................ 5629
Border ................................................................................................................ 5630
BmpName ................................................................................................................ 5631
OnCreate ................................................................................................................ 5632
OnShow ................................................................................................................ 5633
OnHide ................................................................................................................ 5634
OnMove ................................................................................................................ 5635
OnChange ................................................................................................................ 5636
CScroll ......................................................................................................................... 5637
Create ................................................................................................................ 5639
OnEvent ................................................................................................................ 5640
MinPos ................................................................................................................ 5641
MaxPos ................................................................................................................ 5642
CurrPos ................................................................................................................ 5643
CreateBack
................................................................................................................ 5644
CreateI nc ................................................................................................................ 5645
CreateDec ................................................................................................................ 5646
CreateThumb
................................................................................................................ 5647
OnClickI nc ................................................................................................................ 5648
OnClickDec................................................................................................................ 5649
OnShow ................................................................................................................ 5650
OnHide ................................................................................................................ 5651
OnChangePos
................................................................................................................ 5652
OnThumbDragStart
................................................................................................................ 5653
OnThumbDragProcess
................................................................................................................ 5654
OnThumbDragEnd
................................................................................................................ 5655
CalcPos ................................................................................................................ 5656
CScrollV......................................................................................................................... 5657
CreateI nc ................................................................................................................ 5663
CreateDec ................................................................................................................ 5664
CreateThumb
................................................................................................................ 5665
z
OnResi e ................................................................................................................ 5666
OnChangePos
................................................................................................................ 5667
OnThumbDragStart
................................................................................................................ 5668
OnThumbDragProcess
................................................................................................................ 5669
OnThumbDragEnd
................................................................................................................ 5670
CalcPos ................................................................................................................ 5671
CScrollH......................................................................................................................... 5672
CreateI nc ................................................................................................................ 5678
CreateDec ................................................................................................................ 5679
CreateThumb
................................................................................................................ 5680
z
OnResi e ................................................................................................................ 5681
OnChangePos
................................................................................................................ 5682
OnThumbDragStart
................................................................................................................ 5683
OnThumbDragProcess
................................................................................................................ 5684

© 2000-2021, MetaQuotes Ltd


65 Content

OnThumbDragEnd
................................................................................................................ 5685
CalcPos ................................................................................................................ 5686
CWndClient
......................................................................................................................... 5687
Create ................................................................................................................ 5690
OnEvent ................................................................................................................ 5691
ColorBackground
................................................................................................................ 5692
ColorBorder
................................................................................................................ 5693
BorderType................................................................................................................ 5694
VScrolled ................................................................................................................ 5695
HScrolled ................................................................................................................ 5696
CreateBack
................................................................................................................ 5697
CreateScrollV
................................................................................................................ 5698
CreateScrollH
................................................................................................................ 5699
z
OnResi e ................................................................................................................ 5700
OnVScrollShow
................................................................................................................ 5701
OnVScrollHide
................................................................................................................ 5702
OnHScrollShow
................................................................................................................ 5703
OnHScrollHide
................................................................................................................ 5704
OnScrollLineDown
................................................................................................................ 5705
OnScrollLineUp
................................................................................................................ 5706
OnScrollLineLeft
................................................................................................................ 5707
OnScrollLineRight
................................................................................................................ 5708
Rebound ................................................................................................................ 5709
CListView
......................................................................................................................... 5710
Create ................................................................................................................ 5716
OnEvent ................................................................................................................ 5717
TotalView ................................................................................................................ 5718
AddI tem ................................................................................................................ 5719
Select ................................................................................................................ 5720
SelectByText
................................................................................................................ 5721
SelectByValue
................................................................................................................ 5722
Value ................................................................................................................ 5723
CreateRow................................................................................................................ 5724
z
OnResi e ................................................................................................................ 5725
OnVScrollShow
................................................................................................................ 5726
OnVScrollHide
................................................................................................................ 5727
OnScrollLineDown
................................................................................................................ 5728
OnScrollLineUp
................................................................................................................ 5729
OnI temClick
................................................................................................................ 5730
Redraw ................................................................................................................ 5731
RowState ................................................................................................................ 5732
CheckView................................................................................................................ 5733
CComboBox
......................................................................................................................... 5734
Create ................................................................................................................ 5740
OnEvent ................................................................................................................ 5741
AddI tem ................................................................................................................ 5742
ListViewI tems
................................................................................................................ 5743
Select ................................................................................................................ 5744
SelectByText
................................................................................................................ 5745
SelectByValue
................................................................................................................ 5746
Value ................................................................................................................ 5747
CreateEdit................................................................................................................ 5748
CreateButton
................................................................................................................ 5749
CreateList ................................................................................................................ 5750
OnClickEdit................................................................................................................ 5751
OnClickButton
................................................................................................................ 5752
OnChangeList
................................................................................................................ 5753
ListShow ................................................................................................................ 5754

© 2000-2021, MetaQuotes Ltd


66 Content

ListHide ................................................................................................................ 5755


CCheckBox
......................................................................................................................... 5756
Create ................................................................................................................ 5762
OnEvent ................................................................................................................ 5763
Text ................................................................................................................ 5764
Color ................................................................................................................ 5765
Checked ................................................................................................................ 5766
Value ................................................................................................................ 5767
CreateButton
................................................................................................................ 5768
CreateLabel
................................................................................................................ 5769
OnClickButton
................................................................................................................ 5770
OnClickLabel
................................................................................................................ 5771
G
CCheck.........................................................................................................................
roup 5772
Create ................................................................................................................ 5778
OnEvent ................................................................................................................ 5779
AddI tem ................................................................................................................ 5780
Value ................................................................................................................ 5781
CreateButton
................................................................................................................ 5782
OnVScrollShow
................................................................................................................ 5783
OnVScrollHide
................................................................................................................ 5784
OnScrollLineDown
................................................................................................................ 5785
OnScrollLineUp
................................................................................................................ 5786
OnChangeI................................................................................................................
tem 5787
Redraw ................................................................................................................ 5788
RowState ................................................................................................................ 5789
CRadioButton
......................................................................................................................... 5790
Create ................................................................................................................ 5792
OnEvent ................................................................................................................ 5793
Text ................................................................................................................ 5794
Color ................................................................................................................ 5795
State ................................................................................................................ 5796
CreateButton
................................................................................................................ 5797
CreateLabel
................................................................................................................ 5798
OnClickButton
................................................................................................................ 5799
OnClickLabel
................................................................................................................ 5800
G
CRadio .........................................................................................................................
roup 5801
Create ................................................................................................................ 5807
OnEvent ................................................................................................................ 5808
AddI tem ................................................................................................................ 5809
Value ................................................................................................................ 5810
CreateButton
................................................................................................................ 5811
OnVScrollShow
................................................................................................................ 5812
OnVScrollHide
................................................................................................................ 5813
OnScrollLineDown
................................................................................................................ 5814
OnScrollLineUp
................................................................................................................ 5815
OnChangeI................................................................................................................
tem 5816
Redraw ................................................................................................................ 5817
RowState ................................................................................................................ 5818
Select ................................................................................................................ 5819
CSpinEdit
......................................................................................................................... 5820
Create ................................................................................................................ 5825
OnEvent ................................................................................................................ 5826
MinValue ................................................................................................................ 5827
MaxValue ................................................................................................................ 5828
Value ................................................................................................................ 5829
CreateEdit................................................................................................................ 5830
CreateI nc ................................................................................................................ 5831
CreateDec ................................................................................................................ 5832

© 2000-2021, MetaQuotes Ltd


67 Content

OnClickI nc ................................................................................................................ 5833


OnClickDec................................................................................................................ 5834
OnChangeValue
................................................................................................................ 5835
CDialog ......................................................................................................................... 5836
Create ................................................................................................................ 5838
OnEvent ................................................................................................................ 5839
Caption ................................................................................................................ 5840
Add ................................................................................................................ 5841
CreateWhiteBorder
................................................................................................................ 5842
CreateBackground
................................................................................................................ 5843
CreateCaption
................................................................................................................ 5844
CreateButtonClose
................................................................................................................ 5845
CreateClientArea
................................................................................................................ 5846
OnClickCaption
................................................................................................................ 5847
OnClickButtonClose
................................................................................................................ 5848
ClientAreaVisible
................................................................................................................ 5849
ClientAreaLeft
................................................................................................................ 5850
ClientAreaTop
................................................................................................................ 5851
ClientAreaRight
................................................................................................................ 5852
ClientAreaBottom
................................................................................................................ 5853
ClientAreaWidth
................................................................................................................ 5854
ClientAreaHeight
................................................................................................................ 5855
OnDialogDragStart
................................................................................................................ 5856
OnDialogDragProcess
................................................................................................................ 5857
OnDialogDragEnd
................................................................................................................ 5858
CAppDialog
......................................................................................................................... 5859
Create ................................................................................................................ 5862
Destroy ................................................................................................................ 5863
OnEvent ................................................................................................................ 5864
Run ................................................................................................................ 5865
ChartEvent................................................................................................................ 5866
z
Minimi ed ................................................................................................................ 5867
I niFileSave ................................................................................................................ 5868
I niFileLoad................................................................................................................ 5869
I niFileName................................................................................................................ 5870
I niFileExt ................................................................................................................ 5871
CreateCommon
................................................................................................................ 5872
CreateExpert
................................................................................................................ 5873
CreateI ndicator
................................................................................................................ 5874
CreateButtonMinMax
................................................................................................................ 5875
OnClickButtonClose
................................................................................................................ 5876
OnClickButtonMinMax
................................................................................................................ 5877
OnAnotherApplicationClose
................................................................................................................ 5878
Rebound ................................................................................................................ 5879
z
Minimi e ................................................................................................................ 5880
Maximiz e ................................................................................................................ 5881
CreateI nstanceI
................................................................................................................
d 5882
ProgramName
................................................................................................................ 5883
SubwinOff ................................................................................................................ 5884

34 Moving from .................................................................................................


MQL4 5885
35 List of MQL5 .................................................................................................
Functions 5888
36 List of MQL5 .................................................................................................
Constants 5924

© 2000-2021, MetaQuotes Ltd


68

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

Types of MQL5 Applications


MQL5 programs are divided into four 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 .

© 2000-2021, MetaQuotes Ltd


69

· Script is a program for a single execution of an action. Unlike 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 .
· Include File is a source text of the most frequently used block s 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-2021, MetaQuotes Ltd.

© 2000-2021, MetaQuotes Ltd


70 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-2021, MetaQuotes Ltd


71 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-2021, MetaQuotes Ltd


72 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-2021, MetaQuotes Ltd


73 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-2021, MetaQuotes Ltd


74 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-2021, MetaQuotes Ltd


75 Language Basics

this #define #import

false #ifndef #property

template #else group


typename #endif namespace

© 2000-2021, MetaQuotes Ltd


76 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-2021, MetaQuotes Ltd


77 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-2021, MetaQuotes Ltd


78 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-2021, MetaQuotes Ltd


79 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-2021, MetaQuotes Ltd


80 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-2021, MetaQuotes Ltd


81 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-2021, MetaQuotes Ltd


82 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-2021, MetaQuotes Ltd


83 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-2021, MetaQuotes Ltd


84 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-2021, MetaQuotes Ltd


85 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-2021, MetaQuotes Ltd


86 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-2021, MetaQuotes Ltd


87 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-2021, MetaQuotes Ltd


88 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-2021, MetaQuotes Ltd


89 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-2021, MetaQuotes Ltd


90 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

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.

© 2000-2021, MetaQuotes Ltd


91 Language Basics

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

© 2000-2021, MetaQuotes Ltd


92 Language Basics

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

© 2000-2021, MetaQuotes Ltd


93 Language Basics

struct str2
{
long l;
};

//--- Start
str1 s1;
str2 s2;
//---
s1.d=MathArcsin(2.0); // Get the invalid number -1.#IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFFF000000000000; // invalid number -1.#QNAN
s1=s2;
printf("2. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF7000000000000; // greatest 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);
//---

© 2000-2021, MetaQuotes Ltd


94 Language Basics

s2.l=0x7FEFFFFFFFFFFFFF; // Greatest normalized number (MAX_DBL)


s1=s2;
printf("11. %.16e %I64X",s1.d,s2.l);
//---
s2.l=0x0010000000000000; // Smallest positive normalized (MIN_DBL)
s1=s2;
printf("12. %.16e %.16I64X",s1.d,s2.l);
//---
s1.d=0.7; // Show that the number of 0.7 - endless fraction
s2=s1;
printf("13. %.16e %.16I64X",s1.d,s2.l);
/*
1. -1.#IND00 FFF8000000000000
2. -1.#QNAN0 FFFF000000000000
3. 1.#SNAN0 7FF7000000000000
4. 1.#QNAN0 7FF8000000000000
5. 1.#QNAN0 7FFF000000000000
6. 1.#INF00 7FF0000000000000
7. -1.#INF00 FFF0000000000000
8. -0.000000 8000000000000000
9. 0.500000 3FE0000000000000
10. 1.000000 3FF0000000000000
11. 1.7976931348623157e+308 7FEFFFFFFFFFFFFF
12. 2.2250738585072014e-308 0010000000000000
13. 6.9999999999999996e-001 3FE6666666666666
*/

See also
DoubleToS tring, NormalizeDouble, Numeric Type Constants

© 2000-2021, MetaQuotes Ltd


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

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

© 2000-2021, MetaQuotes Ltd


96 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-2021, MetaQuotes Ltd


97 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-2021, MetaQuotes Ltd


98 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-2021, MetaQuotes Ltd


99 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-2021, MetaQuotes Ltd


100 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-2021, MetaQuotes Ltd


101 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-2021, MetaQuotes Ltd


102 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-2021, MetaQuotes Ltd


103 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-2021, MetaQuotes Ltd


104 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-2021, MetaQuotes Ltd


105 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-2021, MetaQuotes Ltd


106 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-2021, MetaQuotes Ltd


107 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-2021, MetaQuotes Ltd


108 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-2021, MetaQuotes Ltd


109 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-2021, MetaQuotes Ltd


110 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-2021, MetaQuotes Ltd


111 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-2021, MetaQuotes Ltd


112 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-2021, MetaQuotes Ltd


113 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-2021, MetaQuotes Ltd


114 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-2021, MetaQuotes Ltd


115 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-2021, MetaQuotes Ltd


116 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-2021, MetaQuotes Ltd


117 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-2021, MetaQuotes Ltd


118 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-2021, MetaQuotes Ltd


119 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-2021, MetaQuotes Ltd


120 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-2021, MetaQuotes Ltd


121 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-2021, MetaQuotes Ltd


122 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-2021, MetaQuotes Ltd


123 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-2021, MetaQuotes Ltd


124 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-2021, MetaQuotes Ltd


125 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-2021, MetaQuotes Ltd


126 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-2021, MetaQuotes Ltd


127 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-2021, MetaQuotes Ltd


128 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-2021, MetaQuotes Ltd


129 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-2021, MetaQuotes Ltd


130 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-2021, MetaQuotes Ltd


131 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-2021, MetaQuotes Ltd


132 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-2021, MetaQuotes Ltd


133 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-2021, MetaQuotes Ltd


134 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-2021, MetaQuotes Ltd


135 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-2021, MetaQuotes Ltd


136 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-2021, MetaQuotes Ltd


137 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-2021, MetaQuotes Ltd


138 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-2021, MetaQuotes Ltd


139 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-2021, MetaQuotes Ltd


140 Language Basics

Object Pointers
In MQL5, there is a possibility to dynamically create objects of complex type. This is done by the new
operator, which returns a descriptor of the created object. Descriptor is 8 bytes large. S yntactically,
object descriptors in MQL5 are similar to pointers in C++.
Examples:

MyObject* hobject= new MyObject();

In contrast to C++, the hobject variable from example above is not a pointer to memory, but rather an
object descriptor. Furthermore, in MQL5 all objects in function parameters must be passed by
reference. Below are examples of passing objects as function parameters :
class Foo
{
public:
string m_name;
int m_id;
static int s_counter;
//--- constructors and desctructors
Foo(void){Setup("noname");};
Foo(string name){Setup(name);};
~Foo(void){};
//--- initializes object of type Foo
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 an object as variable with its 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); // pointer to an object is converted automatically by compiler

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


Foo foo_objects[5];

© 2000-2021, MetaQuotes Ltd


141 Language Basics

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


PrintObjectsArray(foo_objects); // 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); // separate function for passing an array of pointers

//--- it is obligatory to delete objects created as pointers before termination


delete(foo2);
//--- delete 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);
}
//+------------------------------------------------------------------+
//| Passing an array of objects |
//+------------------------------------------------------------------+
void PrintObjectsArray(Foo &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}
//+------------------------------------------------------------------+
//| Passing an array of pointers to object |
//+------------------------------------------------------------------+
void PrintPointersArray(Foo* &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}

© 2000-2021, MetaQuotes Ltd


142 Language Basics

//+------------------------------------------------------------------+

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

© 2000-2021, MetaQuotes Ltd


143 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-2021, MetaQuotes Ltd


144 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-2021, MetaQuotes Ltd


145 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-2021, MetaQuotes Ltd


146 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-2021, MetaQuotes Ltd


147 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-2021, MetaQuotes Ltd


148 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-2021, MetaQuotes Ltd


149 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-2021, MetaQuotes Ltd


150 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-2021, MetaQuotes Ltd


151 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-2021, MetaQuotes Ltd


152 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-2021, MetaQuotes Ltd


153 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-2021, MetaQuotes Ltd


154 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-2021, MetaQuotes Ltd


155 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-2021, MetaQuotes Ltd


156 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-2021, MetaQuotes Ltd


157 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-2021, MetaQuotes Ltd


158 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-2021, MetaQuotes Ltd


159 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

© 2000-2021, MetaQuotes Ltd


160 Language Basics

Operation Desciption Execution Order

*= Multiplication with assignment


/= Division with assignment
%= 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-2021, MetaQuotes Ltd


161 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)

© 2000-2021, MetaQuotes Ltd


162 Language Basics

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

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

© 2000-2021, MetaQuotes Ltd


163 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-2021, MetaQuotes Ltd


164 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-2021, MetaQuotes Ltd


165 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-2021, MetaQuotes Ltd


166 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-2021, MetaQuotes Ltd


167 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-2021, MetaQuotes Ltd


168 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-2021, MetaQuotes Ltd


169 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-2021, MetaQuotes Ltd


170 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-2021, MetaQuotes Ltd


171 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-2021, MetaQuotes Ltd


172 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-2021, MetaQuotes Ltd


173 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-2021, MetaQuotes Ltd


174 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-2021, MetaQuotes Ltd


175 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-2021, MetaQuotes Ltd


176 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-2021, MetaQuotes Ltd


177 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-2021, MetaQuotes Ltd


178 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-2021, MetaQuotes Ltd


179 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-2021, MetaQuotes Ltd


180 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-2021, MetaQuotes Ltd


181 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-2021, MetaQuotes Ltd


182 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-2021, MetaQuotes Ltd


183 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-2021, MetaQuotes Ltd


184 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-2021, MetaQuotes Ltd


185 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-2021, MetaQuotes Ltd


186 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-2021, MetaQuotes Ltd


187 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-2021, MetaQuotes Ltd


188 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-2021, MetaQuotes Ltd


189 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-2021, MetaQuotes Ltd


190 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-2021, MetaQuotes Ltd


191 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-2021, MetaQuotes Ltd


192 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-2021, MetaQuotes Ltd


193 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-2021, MetaQuotes Ltd


194 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-2021, MetaQuotes Ltd


195 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-2021, MetaQuotes Ltd


196 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-2021, MetaQuotes Ltd


197 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-2021, MetaQuotes Ltd


198 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-2021, MetaQuotes Ltd


199 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-2021, MetaQuotes Ltd


200 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-2021, MetaQuotes Ltd


201 Language Basics

See also
Overload, Virtual Functions, Polymorphism

© 2000-2021, MetaQuotes Ltd


202 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-2021, MetaQuotes Ltd


203 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.
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 uccessful initialization, 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.
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.

© 2000-2021, MetaQuotes Ltd


204 Language Basics

Identifier Description

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

© 2000-2021, MetaQuotes Ltd


205 Language Basics

also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type,
with no parameters :
void OnTick();

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 :

© 2000-2021, MetaQuotes Ltd


206 Language Basics

· 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. 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.

© 2000-2021, MetaQuotes Ltd


207 Language Basics

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.
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 OnTesterInit() function is the handler of the TesterInit event, which is automatically generated
before the start of Expert Advisor optimization in the strategy tester. The function must be defined
with the void type. It has no parameters :
void OnTesterInit();

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.

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

© 2000-2021, MetaQuotes Ltd


208 Language Basics

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

© 2000-2021, MetaQuotes Ltd


209 Language Basics

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

© 2000-2021, MetaQuotes Ltd


210 Language Basics

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


parameter lparam dparam sparam
parameter parameter parameter

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

© 2000-2021, MetaQuotes Ltd


211 Language Basics

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

© 2000-2021, MetaQuotes Ltd


212 Language Basics

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.
For this, 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
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:

© 2000-2021, MetaQuotes Ltd


213 Language Basics

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

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

© 2000-2021, MetaQuotes Ltd


214 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-2021, MetaQuotes Ltd


215 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.

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

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-2021, MetaQuotes Ltd


216 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-2021, MetaQuotes Ltd


217 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-2021, MetaQuotes Ltd


218 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-2021, MetaQuotes Ltd


219 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-2021, MetaQuotes Ltd


220 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-2021, MetaQuotes Ltd


221 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-2021, MetaQuotes Ltd


222 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-2021, MetaQuotes Ltd


223 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-2021, MetaQuotes Ltd


224 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-2021, MetaQuotes Ltd


225 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-2021, MetaQuotes Ltd


226 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-2021, MetaQuotes Ltd


227 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-2021, MetaQuotes Ltd


228 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-2021, MetaQuotes Ltd


229 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-2021, MetaQuotes Ltd


230 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-2021, MetaQuotes Ltd


231 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-2021, MetaQuotes Ltd


232 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-2021, MetaQuotes Ltd


233 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-2021, MetaQuotes Ltd


234 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-2021, MetaQuotes Ltd


235 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 program when execution exits when the delete
is unloaded the declaration block operator is executed

© 2000-2021, MetaQuotes Ltd


236 Language Basics

Global automatic Local automatic Dynamically created


variable variable object

or before a mql5
program is unloaded
Deinitialization in the order opposite in the order opposite irrespective of the
order 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-2021, MetaQuotes Ltd


237 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-2021, MetaQuotes Ltd


238 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-2021, MetaQuotes Ltd


239 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-2021, MetaQuotes Ltd


240 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-2021, MetaQuotes Ltd


241 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-2021, MetaQuotes Ltd


242 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

© 2000-2021, MetaQuotes Ltd


243 Language Basics

Constant Type Description

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 howthe indicator in a separate
window
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 T YL E. N is the
number of graphic series ;
numbering starts from 1

© 2000-2021, MetaQuotes Ltd


244 Language Basics

Constant Type Description

indicator_typeN int Type of graphical plotting,


specified by the values of
ENUM _DRAW_T YPE. N is the
number of graphic series ;
numbering starts from 1
indicator_levelN double H orizontallevel 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 tyleof 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 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

© 2000-2021, MetaQuotes Ltd


245 Language Basics

Constant Type Description

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

© 2000-2021, MetaQuotes Ltd


246 Language Basics

Constant Type Description

tester_no_cache property. The test


results are still stored in the 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 pecifies the 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

© 2000-2021, MetaQuotes Ltd


247 Language Basics

Constant Type Description

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.
· "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

© 2000-2021, MetaQuotes Ltd


248 Language Basics

Constant Type Description

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" )

#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-2021, MetaQuotes Ltd


249 Language Basics

© 2000-2021, MetaQuotes Ltd


250 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-2021, MetaQuotes Ltd


251 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-2021, MetaQuotes Ltd


252 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-2021, MetaQuotes Ltd


253 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-2021, MetaQuotes Ltd


254 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-2021, MetaQuotes Ltd


255 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-2021, MetaQuotes Ltd


256 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-2021, MetaQuotes Ltd


257 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-2021, MetaQuotes Ltd


258 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-2021, MetaQuotes Ltd


259 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-2021, MetaQuotes Ltd


260 Language Basics

See also
Data Types

© 2000-2021, MetaQuotes Ltd


261 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-2021, MetaQuotes Ltd


262 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-2021, MetaQuotes Ltd


263 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 2011, MetaQuotes Software Corp."
#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-2021, MetaQuotes Ltd


264 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-2021, MetaQuotes Ltd


265 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-2021, MetaQuotes Ltd


266 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-2021, MetaQuotes Ltd


267 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-2021, MetaQuotes Ltd


268 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-2021, MetaQuotes Ltd


269 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-2021, MetaQuotes Ltd


270 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-2021, MetaQuotes Ltd


271 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-2021, MetaQuotes Ltd


272 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-2021, MetaQuotes Ltd


273 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-2021, MetaQuotes Ltd


274 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-2021, MetaQuotes Ltd


275 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-2021, MetaQuotes Ltd


276 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-2021, MetaQuotes Ltd


277 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-2021, MetaQuotes Ltd


278 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-2021, MetaQuotes Ltd


279 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-2021, MetaQuotes Ltd


280 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-2021, MetaQuotes Ltd


281 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-2021, MetaQuotes Ltd


282 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-2021, MetaQuotes Ltd


283 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-2021, MetaQuotes Ltd


284 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-2021, MetaQuotes Ltd


285 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-2021, MetaQuotes Ltd


286 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-2021, MetaQuotes Ltd


287 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-2021, MetaQuotes Ltd


288 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