MQL 5
MQL 5
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
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
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
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
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
............................................................................................................................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
............................................................................................................................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
............................................................................................................................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
_
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
_
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
· 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.
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
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
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:
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:
See also
Variables, Functions
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
Access Specificators
Memory Classes
Operators
Other
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
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.
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
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;
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);
}
}
for(char ch=-128;ch<=127;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
if(ch==127) break;
}
}
Result:
...
Examples:
H exadecimal: numbers 0-9, the letters a-f or A-F for the values of 10-15; start with 0x or 0X.
Examples:
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
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
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:
backslash \ '\\' 92
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()
{
//---
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()
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:
See also
S tructure of the Date Type, Date and Time, TimeToS tring, S tringToTime
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.
//--- 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
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");
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");
See also
Boolean Operations, Precedence Rules
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
};
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:
Notes
· 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
The double name means that the accuracy of these numbers is twice the accuracy of the float type
numbers. In most cases, the double type is the most convenient one. In many cases the limited
precision of float numbers is not enough. The reason why the float type is still used is saving the
memory (this is important for large arrays of real numbers).
Floating-point constants consist of an integer part, a point (.) and the fractional part. The integer and
fractional parts are sequences of decimal digits.
Examples:
double a=12.111;
double b=-956.1007;
float c =0.0001;
float d =16;
There is a scientific way of writing real constants, often this method of recording is more compact
than the traditional one.
Example:
double c1=1.12123515e-25;
double c2=0.000000000000000000000000112123515; // 24 zero after the decimal point
Print("1. c1 =",DoubleToString(c1,16));
// Result: 1. c1 = 0.0000000000000000
Print("2. c1 =",DoubleToString(c1,-16));
// Result: 2. c1 = 1.1212351499999999e-025
Print("3. c2 =",DoubleToString(c2,-16));
// Result: 3. c2 = 1.1212351499999999e-025
It should be remembered that real numbers are stored in memory with some limited accuracy in the
binary system, while generally the decimal notation is used. That's why many numbers that are
precisely represented in the decimal system can be written only as an infinite fraction in the binary
system.
Forexample, numbers 0.3 and 0.7 are represented in the computer as infinite fractions, while the
number of 0.25 is stored exactly, because it represents the power of two.
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:
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:
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:
Besides the minus infinity there is the plus infinity and NaN (not a number). To determine that this
number is invalid, you can use MathIs ValidNumber(). According to the IEEE standard, they have a
special machine representation. For example, plus infinity for the double type has the bit
representation of 0x7FF0 0000 0000 0000.
Examples:
struct str1
{
double d;
};
struct str2
{
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);
//---
See also
DoubleToS tring, NormalizeDouble, Numeric Type Constants
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:
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
Structure Declaration
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.
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))
{
//--- 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
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
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.
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
};
//--- 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;
The special pack attribute allows setting the alignment of structure or class fields.
pack([n])
'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
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
};
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
};
//--- 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:
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
*/
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
};
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};
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;
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
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:
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);};
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
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();
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
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.
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
{
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;
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);
}
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();
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
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 '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
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
};
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
{
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 :
· 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)
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
};
//+------------------------------------------------------------------+
//| 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
*/
}
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
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:
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:
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
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:
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
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.
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);
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:
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
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 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));
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
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 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
//--- 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
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.
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.
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.
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;}
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());
//---
}
//+------------------------------------------------------------------+
//| 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.
//--- 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.
}
//+------------------------------------------------------------------+
//| 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
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:
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
//+------------------------------------------------------------------+
See also
Variables, Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and
Deleting Objects
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
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
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
Expressions
An expression consists of one or more operands and operation symbols. An expression can be written
in several lines.
Examples:
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
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
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:
See also
Precedence Rules
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 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 (&&) 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).
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");
}
}
//+------------------------------------------------------------------+
See also
Precedence Rules
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);
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.
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
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:
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:
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.
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:
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;
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.
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();
}
//+------------------------------------------------------------------+
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));
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.
To change the operation execution order, parenthesis that are of higher priority are used.
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
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)
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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
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.
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
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:
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
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:
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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);
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:
bool Expression1=true;
double Expression2=M_PI;
string Expression3="3.1415926";
void OnStart()
{
func(Expression2);
func(Expression3);
// 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
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:
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
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:
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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
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:
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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:
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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:
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
//+------------------------------------------------------------------+
//| 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();
}
//---
}
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects
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:
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);
}
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
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:
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
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;
//---
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;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void func(int par1,int par2,string comment)
{
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
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");
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.
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.
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);
See also
Overload, Virtual Functions, Polymorphism
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;
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)); }
z=a*b;
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a/b;
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;
}
//+------------------------------------------------------------------+
//| 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;
}
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
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]]);
}
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());
//--- 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++)
{
//--- 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];
}
//---
}
//+------------------------------------------------------------------+
//| 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
{
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 |
//+------------------------------------------------------------------+
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
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
{
See also
Overloading, Arithmetic Operations, Function Overloading, Precedence Rules
#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();
}
See also
Overload, Virtual Functions, Polymorphism
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
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
Identifier Description
The OnInit() function of the void type always denotes successful initialization.
OnDeinit
The OnDeinit() function is called during deinitialization and is the Deinit event handler. It must be
declared as the void type and should have one parameter of the const int type, which contains the
code of deinitialization reason. If a different type is declared, the compiler will generate a warning,
but the function will not be called. For scripts the Deinit event is not generated and therefore the
OnDeinit() function can't be used in scripts.
void OnDeinit(const int reason);
The Deinit event is generated for Expert Advisors and indicators in the following cases :
· before reinitialization due to the change of a symbol or chart period, to which the mql5 program is
attached;
· before reinitialization due to the change of input parameters ;
· before unloading the mql5 program.
OnTick
The NewTick event is generated for Expert Advisors only when a new tick for a symbol is received, to
the chart of which the Expert Advisor is attached. It's useless to define the OnTick() function in a
custom indicator or script, because the NewTick event is not generated for them.
The Tick event is generated only for Expert Advisors, but this does not mean that Expert Advisors
required the OnTick() function, since not only NewTick events are generated for Expert Advisors, but
also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type,
with no parameters :
void OnTick();
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 :
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.
After applying trade transactions for a client account, they are consistently placed to the terminal
trade transactions queue, from which they consistently sent to OnTradeTransaction entry point in
order of arrival at the terminal.
W hen handling trade transactions by an Expert Advisor using OnTradeTransaction handler, the
terminal continues handling newly arrived trade transactions. Therefore, the state of a trade account
can change during OnTradeTransaction operation already. For example, while an MQL5 program
handles an event of adding a new order, it may be executed, deleted from the list of the open ones
and moved to the history. Further on, the application will be notified of these events.
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();
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
· 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.
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
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.
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
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:
#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
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';
You can't declare variables of the structure type until you declare the structure.
Arrays
Only an integer can be an array index. No more than four-dimensional arrays are allowed. Numbering
of array elements starts with 0. The last element of a one-dimensional array has the number which is 1
less than the array size. This means that call for the last element of an array consisting of 50 integers
will appear as a[49]. The same concerns multidimensional arrays : A dimension is indexed from 0 to
the dimension size-1. The last element of a two-dimensional array from the example will appear as
m[6][49].
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:
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
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
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
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:
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:
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:
z[i]=OrderOpenPrice();
}
x=i;
y=calculated_tp;
}
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
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
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:
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
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 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:
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).
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.
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.
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.
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
(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.
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 :
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
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
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]);
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
for(i=limit;i<rates_total;i++)
{
sum=0;
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
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.
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
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
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
*/
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.
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
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
The #undef directive cancels declaration of the macro substitution, defined before.
Example:
#define MACRO
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
The compiler will write declared values in the configuration of the module executed.
By specifying the
tester_everytick_calculate
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"
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
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
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);
}
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);
}
#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.
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
}
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.
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
S ome of these concepts are rather vague, some are abstract, others are general.
Example:
class CPerson
{
protected:
string m_name; // name
public:
void SetName(string n){m_name=n;}// sets name
string GetName(){return (m_name);} // returns name
};
This approach offers several advantages. 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);
}
See also
Data Types
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:
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 :
public:
CCircle(){m_type=1;}// constructor, type 1
};
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.
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
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());
//--- 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
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:
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
};
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
//--- Create another CCircle object and write down its pointer in shapes[1]
circle=new CCircle();
shapes[1]=circle;
circle.SetRadius(5);
//--- 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;
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
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
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[]);
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:
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;
//---
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 { }
};
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 { }
};
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
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:
//+------------------------------------------------------------------+
//| Class "Stack" for storing processed data |
//+------------------------------------------------------------------+
class CStack
{
public:
CStack(void);
~CStack(void){};
...
private:
static const int s_max_length; // Maximum stack capacity
};
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;
//+------------------------------------------------------------------+
//| 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)
{
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
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):
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();
}
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.
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));
}
Function templates should not be declared with export, virtual and #import keywords.
//+------------------------------------------------------------------+
//| 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
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[])
{
...
}
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.
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);
}
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.
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]);
}
//+------------------------------------------------------------------+
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[])
{
...
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