MQL5 Language Reference PDF
MQL5 Language Reference PDF
Content
MQL5 Reference 38
1 Language Basics................................................................................................. 39
Sy ntax ............................................................................................................................40
Comments......................................................................................................................... 41
Identifiers......................................................................................................................... 42
Reserved .........................................................................................................................
Words 43
Data Ty pes ............................................................................................................................45
Integer Types
......................................................................................................................... 46
Char, Short, Int................................................................................................................
and Long Types 47
Character Constants
................................................................................................................ 50
Datetime Type ................................................................................................................ 53
Color Type ................................................................................................................ 54
Bool Type ................................................................................................................ 55
Enumerations................................................................................................................ 56
Real Types......................................................................................................................... 58
String Type......................................................................................................................... 63
Structures.........................................................................................................................
and Classes 64
Dynamic Array
.........................................................................................................................
Object 75
Typecasting......................................................................................................................... 77
Void Type.........................................................................................................................
and NULL Constant 83
Object Pointers
......................................................................................................................... 84
Reference. .........................................................................................................................
Modifier & and Keyword this 85
............................................................................................................................87
Operations and Expressions
Expressions......................................................................................................................... 88
Arithmetical
.........................................................................................................................
Operations 89
Assignment .........................................................................................................................
Operations 90
Operations .........................................................................................................................
of Relation 91
Boolean Operations
......................................................................................................................... 92
Bitwise Operations
......................................................................................................................... 94
Other Operations
......................................................................................................................... 97
Precedence
.........................................................................................................................
Rules 101
Operators ............................................................................................................................103
Compound .........................................................................................................................
Operator 105
Expression
.........................................................................................................................
Operator 106
Return Operator
......................................................................................................................... 107
Conditional
.........................................................................................................................
Operator if-else 108
Conditional
.........................................................................................................................
Operator ?: 109
Switch Operator
......................................................................................................................... 111
Loop Operator
.........................................................................................................................
while 113
Loop Operator
.........................................................................................................................
for 114
Loop Operator
.........................................................................................................................
do while 115
Break Operator
......................................................................................................................... 116
Continue.........................................................................................................................
Operator 117
Object Create
.........................................................................................................................
Operator new 118
Object Delete
.........................................................................................................................
Operator delete 119
Functions ............................................................................................................................120
Function.........................................................................................................................
Call 122
Passing Parameters
......................................................................................................................... 123
Function.........................................................................................................................
Overloading 126
Description
.........................................................................................................................
of External Functions 129
Exporting.........................................................................................................................
Functions 130
Event Handling
.........................................................................................................................
Functions 131
V ariables ............................................................................................................................139
Local Variables
......................................................................................................................... 142
Formal Parameters
......................................................................................................................... 144
Static Variables
......................................................................................................................... 146
Global Variables
......................................................................................................................... 148
Input Variables
......................................................................................................................... 149
Extern Variables
......................................................................................................................... 152
Initialization
.........................................................................................................................
of Variables 153
Visibility .........................................................................................................................
Scope and Lifetime of Variables 155
Creating.........................................................................................................................
and Deleting Objects 157
Preprocessor............................................................................................................................160
Macro substitution
.........................................................................................................................
(#define) 161
Program.........................................................................................................................
Properties (#property) 163
Including.........................................................................................................................
Files (#include) 167
Importing .........................................................................................................................
Functions (#import) 168
............................................................................................................................170
Object-Oriented Programming
Encapsulation
.........................................................................................................................
and Extensibility of Types 172
Inheritance......................................................................................................................... 175
Polymorphism
......................................................................................................................... 178
Overload......................................................................................................................... 182
Virtual Functions
......................................................................................................................... 183
2 Standard Constants,
.................................................................................................
Enumerations and Structures 186
............................................................................................................................187
Chart Constants
Types of .........................................................................................................................
Chart Events 188
Chart Timeframes
......................................................................................................................... 192
Chart Properties
......................................................................................................................... 194
Positioning
.........................................................................................................................
Constants 198
Chart Representation
......................................................................................................................... 199
............................................................................................................................201
Objects Constants
Object Types
......................................................................................................................... 202
Object Properties
......................................................................................................................... 204
Methods .........................................................................................................................
of Object Binding 209
Chart Corner
......................................................................................................................... 213
Visibility .........................................................................................................................
of Objects 215
Levels of.........................................................................................................................
Elliott Wave 218
Gann Objects
......................................................................................................................... 219
Web Colors ......................................................................................................................... 221
Wingdings ......................................................................................................................... 223
............................................................................................................................224
Indicator Constants
Price Constants
......................................................................................................................... 225
Smoothing.........................................................................................................................
Methods 228
Indicators
.........................................................................................................................
Lines 229
Drawing .........................................................................................................................
Styles 231
Custom Indicator
.........................................................................................................................
Properties 235
Indicator.........................................................................................................................
Types 238
Data Type.........................................................................................................................
Identifiers 240
Environment ............................................................................................................................241
State
Client Terminal
.........................................................................................................................
Properties 242
Running MQL5
.........................................................................................................................
Program Properties 244
Symbol Properties
......................................................................................................................... 246
Account .........................................................................................................................
Properties 253
Testing Statistics
......................................................................................................................... 255
............................................................................................................................259
Trade Constants
History Database
.........................................................................................................................
Properties 260
Order Properties
......................................................................................................................... 261
Position .........................................................................................................................
Properties 265
Deal Properties
......................................................................................................................... 267
Trade Operation
.........................................................................................................................
Types 269
Trade Orders
.........................................................................................................................
in DOM 270
............................................................................................................................271
Named Constants
Predefined.........................................................................................................................
Macrosubstitutions 272
Mathematical
.........................................................................................................................
Constants 274
Numerical .........................................................................................................................
Type Constants 276
Uninitalization
.........................................................................................................................
Reason Codes 279
Checking.........................................................................................................................
Object Pointer 281
Other Constants
......................................................................................................................... 282
............................................................................................................................285
Data Structures
Structure .........................................................................................................................
of the Date Type 286
Structure .........................................................................................................................
of Input Parameters 287
History Data
.........................................................................................................................
Structure 288
DOM Structure
......................................................................................................................... 289
Trade Request
.........................................................................................................................
Structure 290
Structure .........................................................................................................................
of Request Check Results 294
Structure .........................................................................................................................
of a Trade Request Result 295
Structure .........................................................................................................................
for Current Prices 298
............................................................................................................................299
Codes of Errors and W arnings
Trade Server
.........................................................................................................................
Return Codes 300
Compiler.........................................................................................................................
Warnings 302
Compilation
.........................................................................................................................
Errors 305
Runtime .........................................................................................................................
Errors 314
Input/Output ............................................................................................................................321
Constants
File Opening
.........................................................................................................................
Flags 322
In-File Position
......................................................................................................................... 324
Use of a .........................................................................................................................
Codepage 325
MessageBox......................................................................................................................... 326
3 MQL5 programs
................................................................................................. 328
............................................................................................................................329
Program Running
............................................................................................................................334
Client Terminal Events
Resources ............................................................................................................................337
............................................................................................................................344
Call of Imported Functions
............................................................................................................................346
Runtime Errors
4 Predefined Variables
................................................................................................. 347
_Digits ............................................................................................................................348
_Point ............................................................................................................................349
_LastError ............................................................................................................................350
_Period ............................................................................................................................351
_StopFlag ............................................................................................................................352
_Sy mbol ............................................................................................................................353
............................................................................................................................354
_UninitReason
5 Common Functions
................................................................................................. 355
Alert ............................................................................................................................356
............................................................................................................................357
CheckPointer
Comment ............................................................................................................................359
DebugBreak ............................................................................................................................360
............................................................................................................................361
ExpertRemove
GetPointer ............................................................................................................................363
............................................................................................................................367
GetTickCount
MessageBox............................................................................................................................368
............................................................................................................................369
PeriodSeconds
Play Sound ............................................................................................................................370
Print ............................................................................................................................371
PrintFormat............................................................................................................................372
............................................................................................................................377
ResetLastError
............................................................................................................................378
SetUserError
SendFTP ............................................................................................................................379
SendMail ............................................................................................................................380
Sleep ............................................................................................................................381
............................................................................................................................382
TerminalClose
............................................................................................................................384
TesterStatistics
............................................................................................................................385
TesterW ithdraw al
ZeroMemory ............................................................................................................................386
6 Array Functions
................................................................................................. 387
Array Bsearch............................................................................................................................388
Array Copy ............................................................................................................................390
Array Free ............................................................................................................................391
............................................................................................................................392
Array GetAsSeries
............................................................................................................................393
Array Initialize
............................................................................................................................394
Array IsDy namic
............................................................................................................................395
Array IsSeries
Array Maximum............................................................................................................................397
Array Minimum............................................................................................................................398
Array Range............................................................................................................................399
Array Resize ............................................................................................................................400
............................................................................................................................401
Array SetAsSeries
Array Size ............................................................................................................................404
Array Sort ............................................................................................................................405
7 Conversion Functions
................................................................................................. 406
............................................................................................................................408
CharToString
............................................................................................................................409
CharArray ToString
............................................................................................................................410
ColorToString
............................................................................................................................411
DoubleToString
............................................................................................................................412
EnumToString
............................................................................................................................414
IntegerToString
............................................................................................................................415
ShortToString
ShortArray............................................................................................................................416
ToString
............................................................................................................................417
TimeToString
............................................................................................................................418
NormalizeDouble
............................................................................................................................419
StringToCharArray
............................................................................................................................420
StringToColor
............................................................................................................................421
StringToDouble
............................................................................................................................422
StringToInteger
............................................................................................................................423
StringToShortArray
............................................................................................................................424
StringToTime
............................................................................................................................425
StringFormat
8 Math Functions
................................................................................................. 426
MathAbs ............................................................................................................................427
MathArccos............................................................................................................................428
MathArcsin............................................................................................................................429
MathArctan............................................................................................................................430
MathCeil ............................................................................................................................431
MathCos ............................................................................................................................432
MathExp ............................................................................................................................433
MathFloor ............................................................................................................................434
MathLog ............................................................................................................................435
MathLog10 ............................................................................................................................436
MathMax ............................................................................................................................437
MathMin ............................................................................................................................438
MathMod ............................................................................................................................439
MathPow ............................................................................................................................440
MathRand ............................................................................................................................441
MathRound............................................................................................................................442
MathSin ............................................................................................................................443
MathSqrt ............................................................................................................................444
MathSrand ............................................................................................................................445
MathTan ............................................................................................................................446
............................................................................................................................447
MathIsV alidNumber
9 String Functions
................................................................................................. 448
StringAdd ............................................................................................................................449
............................................................................................................................451
StringBufferLen
............................................................................................................................452
StringCompare
............................................................................................................................454
StringConcatenate
StringFill ............................................................................................................................455
StringFind ............................................................................................................................456
............................................................................................................................457
StringGetCharacter
StringInit ............................................................................................................................458
StringLen ............................................................................................................................459
............................................................................................................................460
StringReplace
............................................................................................................................461
StringSetCharacter
............................................................................................................................463
StringSubstr
StringToLow............................................................................................................................464
er
............................................................................................................................465
StringToUpper
............................................................................................................................466
StringTrimLeft
............................................................................................................................467
StringTrimRight
10 Date and Time................................................................................................. 468
TimeCurrent............................................................................................................................469
............................................................................................................................470
TimeTradeServer
TimeLocal ............................................................................................................................471
TimeGMT ............................................................................................................................472
............................................................................................................................473
TimeDay lightSavings
............................................................................................................................474
TimeGMTOffset
............................................................................................................................475
TimeToStruct
............................................................................................................................476
StructToTime
11 Account Information
................................................................................................. 477
............................................................................................................................478
AccountInfoDouble
............................................................................................................................479
AccountInfoInteger
............................................................................................................................481
AccountInfoString
12 Checkup ................................................................................................. 482
GetLastError............................................................................................................................483
IsStopped ............................................................................................................................484
............................................................................................................................485
UninitializeReason
............................................................................................................................486
TerminalInfoInteger
............................................................................................................................487
TerminalInfoString
............................................................................................................................488
MQL5InfoInteger
............................................................................................................................489
MQL5InfoString
Sy mbol ............................................................................................................................490
Period ............................................................................................................................491
Digits ............................................................................................................................492
Point ............................................................................................................................493
13 Market Info ................................................................................................. 494
............................................................................................................................495
Sy mbolsTotal
Sy mbolName............................................................................................................................496
............................................................................................................................497
Sy mbolSelect
Sy mbolIsSy............................................................................................................................498
nchronized
............................................................................................................................499
Sy mbolInfoDouble
............................................................................................................................501
Sy mbolInfoInteger
............................................................................................................................503
Sy mbolInfoString
............................................................................................................................504
Sy mbolInfoTick
............................................................................................................................505
Sy mbolInfoSessionQuote
............................................................................................................................506
Sy mbolInfoSessionTrade
............................................................................................................................507
MarketBookAdd
............................................................................................................................508
MarketBookRelease
............................................................................................................................509
MarketBookGet
14 Timeseries and
.................................................................................................
Indicators Access 510
............................................................................................................................514
Indexing Direction in Array s, Buffers and Timeseries
Organizing ............................................................................................................................517
Data Access
............................................................................................................................526
SeriesInfoInteger
Bars ............................................................................................................................528
............................................................................................................................530
BarsCalculated
............................................................................................................................532
IndicatorCreate
............................................................................................................................534
IndicatorRelease
Copy Buffer............................................................................................................................536
Copy Rates ............................................................................................................................540
Copy Time ............................................................................................................................543
Copy Open ............................................................................................................................546
Copy High ............................................................................................................................549
Copy Low ............................................................................................................................553
Copy Close ............................................................................................................................556
Copy TickV............................................................................................................................559
olume
............................................................................................................................563
Copy RealV olume
Copy Spread............................................................................................................................566
15 Chart Operations
................................................................................................. 570
ChartApply............................................................................................................................572
Template
............................................................................................................................575
ChartW indow Find
ChartOpen ............................................................................................................................577
ChartFirst ............................................................................................................................578
ChartNext ............................................................................................................................579
ChartClose ............................................................................................................................580
............................................................................................................................581
ChartSy mbol
ChartPeriod............................................................................................................................582
ChartRedraw............................................................................................................................583
............................................................................................................................584
ChartSetDouble
............................................................................................................................585
ChartSetInteger
............................................................................................................................586
ChartSetString
............................................................................................................................587
ChartGetDouble
............................................................................................................................589
ChartGetInteger
............................................................................................................................591
ChartGetString
............................................................................................................................593
ChartNavigate
ChartID ............................................................................................................................596
............................................................................................................................597
ChartIndicatorAdd
............................................................................................................................598
ChartIndicatorDelete
............................................................................................................................599
ChartIndicatorName
............................................................................................................................600
ChartIndicatorsTotal
............................................................................................................................601
ChartW indow OnDropped
............................................................................................................................602
ChartPriceOnDropped
............................................................................................................................603
ChartTimeOnDropped
............................................................................................................................604
ChartX OnDropped
............................................................................................................................605
ChartY OnDropped
............................................................................................................................606
ChartSetSy mbolPeriod
............................................................................................................................607
ChartScreenShot
16 Trade Functions
................................................................................................. 608
............................................................................................................................610
OrderCalcMargin
............................................................................................................................611
OrderCalcProfit
OrderCheck ............................................................................................................................612
OrderSend............................................................................................................................613
............................................................................................................................618
PositionsTotal
............................................................................................................................619
PositionGetSy mbol
............................................................................................................................620
PositionSelect
............................................................................................................................621
PositionGetDouble
............................................................................................................................622
PositionGetInteger
............................................................................................................................623
PositionGetString
OrdersTotal ............................................................................................................................624
............................................................................................................................625
OrderGetTicket
OrderSelect ............................................................................................................................627
............................................................................................................................628
OrderGetDouble
............................................................................................................................629
OrderGetInteger
............................................................................................................................630
OrderGetString
............................................................................................................................631
History Select
............................................................................................................................633
History SelectBy Position
............................................................................................................................634
History OrderSelect
............................................................................................................................635
History OrdersTotal
............................................................................................................................636
History OrderGetTicket
............................................................................................................................638
History OrderGetDouble
............................................................................................................................639
History OrderGetInteger
............................................................................................................................640
History OrderGetString
............................................................................................................................641
History DealSelect
............................................................................................................................642
History DealsTotal
............................................................................................................................643
History DealGetTicket
............................................................................................................................646
History DealGetDouble
............................................................................................................................647
History DealGetInteger
............................................................................................................................648
History DealGetString
17 Global Variables
.................................................................................................
of the Terminal 649
............................................................................................................................650
GlobalV ariableCheck
............................................................................................................................651
GlobalV ariableTime
............................................................................................................................652
GlobalV ariableDel
............................................................................................................................653
GlobalV ariableGet
............................................................................................................................654
GlobalV ariableName
............................................................................................................................655
GlobalV ariableSet
............................................................................................................................656
GlobalV ariablesFlush
............................................................................................................................657
GlobalV ariableTemp
............................................................................................................................658
GlobalV ariableSetOnCondition
............................................................................................................................659
GlobalV ariablesDeleteAll
............................................................................................................................660
GlobalV ariablesTotal
18 File Functions................................................................................................. 661
............................................................................................................................664
FileFindFirst
FileFindNext............................................................................................................................666
............................................................................................................................667
FileFindClose
FileIsExist ............................................................................................................................668
FileOpen ............................................................................................................................669
FileClose ............................................................................................................................671
FileCopy ............................................................................................................................672
FileDelete ............................................................................................................................673
FileMove ............................................................................................................................674
FileFlush ............................................................................................................................675
FileIsEnding............................................................................................................................676
............................................................................................................................677
FileIsLineEnding
............................................................................................................................678
FileReadArray
FileReadBool............................................................................................................................679
............................................................................................................................680
FileReadDatetime
............................................................................................................................681
FileReadDouble
............................................................................................................................682
FileReadFloat
............................................................................................................................683
FileReadInteger
FileReadLong............................................................................................................................684
............................................................................................................................685
FileReadNumber
............................................................................................................................686
FileReadString
............................................................................................................................687
FileReadStruct
FileSeek ............................................................................................................................688
FileSize ............................................................................................................................689
FileTell ............................................................................................................................690
FileW rite ............................................................................................................................691
............................................................................................................................692
FileW riteArray
............................................................................................................................693
FileW riteDouble
............................................................................................................................694
FileW riteFloat
............................................................................................................................695
FileW riteInteger
............................................................................................................................696
FileW riteLong
............................................................................................................................697
FileW riteString
............................................................................................................................698
FileW riteStruct
FolderCreate............................................................................................................................699
FolderDelete............................................................................................................................700
FolderClean ............................................................................................................................701
19 Custom Indicators
................................................................................................. 702
Connection............................................................................................................................706
betw een Indicator Properties and Functions
............................................................................................................................708
Indicator Sty les in Examples
DRAW_NONE......................................................................................................................... 715
DRAW_LINE......................................................................................................................... 718
DRAW_SECTION
......................................................................................................................... 722
DRAW_HISTOGRAM
......................................................................................................................... 726
DRAW_HISTOGRAM2
......................................................................................................................... 730
DRAW_ARROW
......................................................................................................................... 734
DRAW_ZIGZAG
......................................................................................................................... 739
DRAW_FILLING
......................................................................................................................... 744
DRAW_BARS......................................................................................................................... 749
DRAW_CANDLES
......................................................................................................................... 755
DRAW_COLOR_LINE
......................................................................................................................... 761
DRAW_COLOR_SECTION
......................................................................................................................... 766
DRAW_COLOR_HISTOGRAM
......................................................................................................................... 772
DRAW_COLOR_HISTOGRAM2
......................................................................................................................... 777
DRAW_COLOR_ARROW
......................................................................................................................... 782
DRAW_COLOR_ZIGZAG
......................................................................................................................... 788
DRAW_COLOR_BARS
......................................................................................................................... 793
DRAW_COLOR_CANDLES
......................................................................................................................... 800
............................................................................................................................807
SetIndexBuffer
............................................................................................................................810
IndicatorSetDouble
............................................................................................................................811
IndicatorSetInteger
............................................................................................................................812
IndicatorSetString
............................................................................................................................813
PlotIndexSetDouble
............................................................................................................................814
PlotIndexSetInteger
............................................................................................................................818
PlotIndexSetString
............................................................................................................................819
PlotIndexGetInteger
20 Object Functions
................................................................................................. 822
............................................................................................................................824
ObjectCreate
ObjectName............................................................................................................................826
............................................................................................................................827
ObjectDelete
............................................................................................................................828
ObjectsDeleteAll
ObjectFind............................................................................................................................829
............................................................................................................................830
ObjectGetTimeBy V alue
ObjectGetV............................................................................................................................831
alueBy Time
ObjectMove............................................................................................................................832
............................................................................................................................833
ObjectsTotal
............................................................................................................................834
ObjectSetDouble
............................................................................................................................837
ObjectSetInteger
............................................................................................................................838
ObjectSetString
............................................................................................................................840
ObjectGetDouble
............................................................................................................................841
ObjectGetInteger
............................................................................................................................842
ObjectGetString
21 Technical Indicators
................................................................................................. 844
iAC ............................................................................................................................847
iAD ............................................................................................................................848
iADX ............................................................................................................................849
iADX W ilder............................................................................................................................850
iAlligator ............................................................................................................................851
iAMA ............................................................................................................................853
iAO ............................................................................................................................854
iATR ............................................................................................................................855
iBearsPow er............................................................................................................................856
iBands ............................................................................................................................857
iBullsPow er............................................................................................................................858
iCCI ............................................................................................................................859
iChaikin ............................................................................................................................860
iCustom ............................................................................................................................861
iDEMA ............................................................................................................................864
iDeMarker ............................................................................................................................865
iEnvelopes ............................................................................................................................866
iForce ............................................................................................................................867
iFractals ............................................................................................................................868
iFrAMA ............................................................................................................................869
iGator ............................................................................................................................870
iIchimoku ............................................................................................................................872
iBW MFI ............................................................................................................................873
iMomentum............................................................................................................................874
iMFI ............................................................................................................................875
iMA ............................................................................................................................876
iOsMA ............................................................................................................................877
iMACD ............................................................................................................................878
iOBV ............................................................................................................................879
iSAR ............................................................................................................................880
iRSI ............................................................................................................................881
iRV I ............................................................................................................................882
iStdDev ............................................................................................................................883
iStochastic ............................................................................................................................884
iTEMA ............................................................................................................................885
iTriX ............................................................................................................................886
iW PR ............................................................................................................................887
iV IDy A ............................................................................................................................888
iV olumes ............................................................................................................................889
22 Working with Events
................................................................................................. 890
............................................................................................................................891
EventSetTimer
............................................................................................................................892
EventKillTimer
............................................................................................................................893
EventChartCustom
23 Standard Library
................................................................................................. 898
Basic Class ............................................................................................................................899
CObject
Prev ......................................................................................................................... 900
Prev ......................................................................................................................... 901
Next ......................................................................................................................... 902
Next ......................................................................................................................... 903
Compare......................................................................................................................... 904
Save ......................................................................................................................... 906
Load ......................................................................................................................... 908
Type ......................................................................................................................... 910
............................................................................................................................911
Classes of data
At ................................................................................................................ 981
CompareArray ................................................................................................................ 983
CompareArray ................................................................................................................ 984
InsertSort ................................................................................................................ 985
Search ................................................................................................................ 986
SearchGreat................................................................................................................ 987
SearchLess ................................................................................................................ 988
SearchGreatOrEqual
................................................................................................................ 989
SearchLessOrEqual
................................................................................................................ 990
SearchFirst ................................................................................................................ 991
SearchLast ................................................................................................................ 992
Save ................................................................................................................ 993
Load ................................................................................................................ 995
Type ................................................................................................................ 997
CArrayInt......................................................................................................................... 998
Reserve ................................................................................................................ 1000
Resize ................................................................................................................ 1001
Shutdown ................................................................................................................ 1002
Add ................................................................................................................ 1003
AddArray ................................................................................................................ 1004
AddArray ................................................................................................................ 1005
Insert ................................................................................................................ 1007
InsertArray................................................................................................................ 1008
InsertArray................................................................................................................ 1009
AssignArray................................................................................................................ 1011
AssignArray................................................................................................................ 1012
Update ................................................................................................................ 1014
Shift ................................................................................................................ 1015
Delete ................................................................................................................ 1016
DeleteRange ................................................................................................................ 1017
At ................................................................................................................ 1018
CompareArray ................................................................................................................ 1020
CompareArray ................................................................................................................ 1021
InsertSort ................................................................................................................ 1022
Search ................................................................................................................ 1023
SearchGreat ................................................................................................................ 1024
SearchLess................................................................................................................ 1025
SearchGreatOrEqual
................................................................................................................ 1026
SearchLessOrEqual
................................................................................................................ 1027
SearchFirst................................................................................................................ 1028
SearchLast................................................................................................................ 1029
Save ................................................................................................................ 1030
Load ................................................................................................................ 1032
Type ................................................................................................................ 1034
CArrayLong
......................................................................................................................... 1035
Reserve ................................................................................................................ 1037
Resize ................................................................................................................ 1038
Shutdown ................................................................................................................ 1039
Add ................................................................................................................ 1040
AddArray ................................................................................................................ 1041
AddArray ................................................................................................................ 1042
Insert ................................................................................................................ 1044
InsertArray................................................................................................................ 1045
InsertArray................................................................................................................ 1046
AssignArray................................................................................................................ 1048
AssignArray................................................................................................................ 1049
Update ................................................................................................................ 1051
Shift ................................................................................................................ 1052
AssignArray................................................................................................................ 1124
AssignArray................................................................................................................ 1125
Update ................................................................................................................ 1127
Shift ................................................................................................................ 1128
Delete ................................................................................................................ 1129
DeleteRange ................................................................................................................ 1130
At ................................................................................................................ 1131
CompareArray ................................................................................................................ 1133
CompareArray ................................................................................................................ 1134
InsertSort ................................................................................................................ 1135
Search ................................................................................................................ 1136
SearchGreat ................................................................................................................ 1137
SearchLess................................................................................................................ 1138
SearchGreatOrEqual
................................................................................................................ 1139
SearchLessOrEqual
................................................................................................................ 1140
SearchFirst................................................................................................................ 1141
SearchLast................................................................................................................ 1142
Save ................................................................................................................ 1143
Load ................................................................................................................ 1145
Type ................................................................................................................ 1147
CArrayString
......................................................................................................................... 1148
Reserve ................................................................................................................ 1150
Resize ................................................................................................................ 1151
Shutdown ................................................................................................................ 1152
Add ................................................................................................................ 1153
AddArray ................................................................................................................ 1154
AddArray ................................................................................................................ 1155
Insert ................................................................................................................ 1157
InsertArray................................................................................................................ 1158
InsertArray................................................................................................................ 1159
AssignArray................................................................................................................ 1161
AssignArray................................................................................................................ 1162
Update ................................................................................................................ 1164
Shift ................................................................................................................ 1165
Delete ................................................................................................................ 1166
DeleteRange ................................................................................................................ 1167
At ................................................................................................................ 1168
CompareArray ................................................................................................................ 1170
CompareArray ................................................................................................................ 1171
InsertSort ................................................................................................................ 1172
Search ................................................................................................................ 1173
SearchGreat ................................................................................................................ 1174
SearchLess................................................................................................................ 1175
SearchGreatOrEqual
................................................................................................................ 1176
SearchLessOrEqual
................................................................................................................ 1177
SearchFirst................................................................................................................ 1178
SearchLast................................................................................................................ 1179
Save ................................................................................................................ 1180
Load ................................................................................................................ 1182
Type ................................................................................................................ 1184
CArrayObj
......................................................................................................................... 1185
FreeMode ................................................................................................................ 1190
FreeMode ................................................................................................................ 1191
Reserve ................................................................................................................ 1193
Resize ................................................................................................................ 1194
Clear ................................................................................................................ 1196
Shutdown ................................................................................................................ 1197
CreateElement................................................................................................................ 1198
VisibleBars
......................................................................................................................... 1593
WindowsTotal
......................................................................................................................... 1594
WindowIsVisible
......................................................................................................................... 1595
WindowHandle
......................................................................................................................... 1596
FirstVisibleBar
......................................................................................................................... 1597
WidthInBars
......................................................................................................................... 1598
WidthInPixels
......................................................................................................................... 1599
HeightInPixels
......................................................................................................................... 1600
PriceMin ......................................................................................................................... 1601
PriceMax ......................................................................................................................... 1602
Attach ......................................................................................................................... 1603
FirstChart
......................................................................................................................... 1604
NextChart......................................................................................................................... 1605
Open ......................................................................................................................... 1606
Detach......................................................................................................................... 1607
Close ......................................................................................................................... 1608
Navigate ......................................................................................................................... 1609
Symbol ......................................................................................................................... 1610
Period ......................................................................................................................... 1611
Redraw......................................................................................................................... 1612
GetInteger
......................................................................................................................... 1613
SetInteger
......................................................................................................................... 1614
GetDouble......................................................................................................................... 1615
SetDouble......................................................................................................................... 1616
GetString......................................................................................................................... 1617
SetString......................................................................................................................... 1618
SetSymbolPeriod
......................................................................................................................... 1619
ApplyTemplate
......................................................................................................................... 1620
ScreenShot
......................................................................................................................... 1621
WindowOnDropped
......................................................................................................................... 1622
PriceOnDropped
......................................................................................................................... 1623
TimeOnDropped
......................................................................................................................... 1624
XOnDropped
......................................................................................................................... 1625
YOnDropped
......................................................................................................................... 1626
Save ......................................................................................................................... 1627
Load ......................................................................................................................... 1628
Type ......................................................................................................................... 1629
Classes for............................................................................................................................1630
file operations
CFile ......................................................................................................................... 1631
Handle ................................................................................................................ 1633
Filename ................................................................................................................ 1634
Flags ................................................................................................................ 1635
SetUnicode................................................................................................................ 1636
SetCommon................................................................................................................ 1637
Open ................................................................................................................ 1638
Close ................................................................................................................ 1639
Delete ................................................................................................................ 1640
IsExist ................................................................................................................ 1641
Copy ................................................................................................................ 1642
Move ................................................................................................................ 1643
Size ................................................................................................................ 1644
Tell ................................................................................................................ 1645
Seek ................................................................................................................ 1646
Flush ................................................................................................................ 1647
IsEnding ................................................................................................................ 1648
IsLineEnding ................................................................................................................ 1649
FolderCreate ................................................................................................................ 1650
FolderDelete ................................................................................................................ 1651
FolderClean................................................................................................................ 1652
FileFindFirst................................................................................................................ 1653
FileFindNext ................................................................................................................ 1654
FileFindClose................................................................................................................ 1655
CFileBin......................................................................................................................... 1656
Open ................................................................................................................ 1658
WriteChar ................................................................................................................ 1659
WriteShort................................................................................................................ 1660
WriteInteger ................................................................................................................ 1661
WriteLong ................................................................................................................ 1662
WriteFloat................................................................................................................ 1663
WriteDouble ................................................................................................................ 1664
WriteString................................................................................................................ 1665
WriteCharArray
................................................................................................................ 1666
WriteShortArray
................................................................................................................ 1667
WriteIntegerArray
................................................................................................................ 1668
WriteLongArray
................................................................................................................ 1669
WriteFloatArray
................................................................................................................ 1670
WriteDoubleArray
................................................................................................................ 1671
WriteObject ................................................................................................................ 1672
ReadChar ................................................................................................................ 1673
ReadShort ................................................................................................................ 1674
ReadInteger ................................................................................................................ 1675
ReadLong ................................................................................................................ 1676
ReadFloat ................................................................................................................ 1677
ReadDouble................................................................................................................ 1678
ReadString................................................................................................................ 1679
ReadCharArray................................................................................................................ 1680
ReadShortArray
................................................................................................................ 1681
ReadIntegerArray
................................................................................................................ 1682
ReadLongArray................................................................................................................ 1683
ReadFloatArray
................................................................................................................ 1684
ReadDoubleArray
................................................................................................................ 1685
ReadObject................................................................................................................ 1686
CFileTxt......................................................................................................................... 1687
Open ................................................................................................................ 1688
WriteString................................................................................................................ 1689
ReadString................................................................................................................ 1690
............................................................................................................................1691
Class for String operations
CString......................................................................................................................... 1692
Str ................................................................................................................ 1694
Len ................................................................................................................ 1695
Copy ................................................................................................................ 1696
Fill ................................................................................................................ 1697
Assign ................................................................................................................ 1698
Append ................................................................................................................ 1699
Insert ................................................................................................................ 1700
Compare ................................................................................................................ 1701
CompareNoCase................................................................................................................ 1702
Left ................................................................................................................ 1703
Right ................................................................................................................ 1704
Mid ................................................................................................................ 1705
Trim ................................................................................................................ 1706
TrimLeft ................................................................................................................ 1707
TrimRight ................................................................................................................ 1708
Clear ................................................................................................................ 1709
ToUpper ................................................................................................................ 1710
ToLower ................................................................................................................ 1711
Oscillators
......................................................................................................................... 1956
CiATR ................................................................................................................ 1957
MaPeriod ........................................................................................................... 1958
Create ........................................................................................................... 1959
Main ........................................................................................................... 1960
Type ........................................................................................................... 1961
CiBearsPower ................................................................................................................ 1962
MaPeriod ........................................................................................................... 1963
Create ........................................................................................................... 1964
Main ........................................................................................................... 1965
Type ........................................................................................................... 1966
CiBullsPower ................................................................................................................ 1967
MaPeriod ........................................................................................................... 1968
Create ........................................................................................................... 1969
Main ........................................................................................................... 1970
Type ........................................................................................................... 1971
CiCCI ................................................................................................................ 1972
MaPeriod ........................................................................................................... 1973
Applied ........................................................................................................... 1974
Create ........................................................................................................... 1975
Main ........................................................................................................... 1976
Type ........................................................................................................... 1977
CiChaikin ................................................................................................................ 1978
FastMaPeriod ........................................................................................................... 1979
SlowMaPeriod ........................................................................................................... 1980
MaMethod ........................................................................................................... 1981
Applied ........................................................................................................... 1982
Create ........................................................................................................... 1983
Main ........................................................................................................... 1984
Type ........................................................................................................... 1985
CiDeMarker................................................................................................................ 1986
MaPeriod ........................................................................................................... 1987
Create ........................................................................................................... 1988
Main ........................................................................................................... 1989
Type ........................................................................................................... 1990
CiForce ................................................................................................................ 1991
MaPeriod ........................................................................................................... 1992
MaMethod ........................................................................................................... 1993
Applied ........................................................................................................... 1994
Create ........................................................................................................... 1995
Main ........................................................................................................... 1996
Type ........................................................................................................... 1997
CiMACD ................................................................................................................ 1998
FastEmaPeriod........................................................................................................... 1999
SlowEmaPeriod........................................................................................................... 2000
SignalPeriod ........................................................................................................... 2001
Applied ........................................................................................................... 2002
Create ........................................................................................................... 2003
Main ........................................................................................................... 2004
Signal ........................................................................................................... 2005
Type ........................................................................................................... 2006
CiMomentum ................................................................................................................ 2007
MaPeriod ........................................................................................................... 2008
Applied ........................................................................................................... 2009
Create ........................................................................................................... 2010
Main ........................................................................................................... 2011
Type ........................................................................................................... 2012
CiOsMA ................................................................................................................ 2013
FastEmaPeriod........................................................................................................... 2014
SlowEmaPeriod........................................................................................................... 2015
SignalPeriod ........................................................................................................... 2016
Applied ........................................................................................................... 2017
Create ........................................................................................................... 2018
Main ........................................................................................................... 2019
Type ........................................................................................................... 2020
CiRSI ................................................................................................................ 2021
MaPeriod ........................................................................................................... 2022
Applied ........................................................................................................... 2023
Create ........................................................................................................... 2024
Main ........................................................................................................... 2025
Type ........................................................................................................... 2026
CiRVI ................................................................................................................ 2027
MaPeriod ........................................................................................................... 2028
Create ........................................................................................................... 2029
Main ........................................................................................................... 2030
Signal ........................................................................................................... 2031
Type ........................................................................................................... 2032
CiStochastic ................................................................................................................ 2033
Kperiod ........................................................................................................... 2034
Dperiod ........................................................................................................... 2035
Slowing ........................................................................................................... 2036
MaMethod ........................................................................................................... 2037
PriceField ........................................................................................................... 2038
Create ........................................................................................................... 2039
Main ........................................................................................................... 2040
Signal ........................................................................................................... 2041
Type ........................................................................................................... 2042
CiTriX ................................................................................................................ 2043
MaPeriod ........................................................................................................... 2044
Applied ........................................................................................................... 2045
Create ........................................................................................................... 2046
Main ........................................................................................................... 2047
Type ........................................................................................................... 2048
CiWPR ................................................................................................................ 2049
CalcPeriod........................................................................................................... 2050
Create ........................................................................................................... 2051
Main ........................................................................................................... 2052
Type ........................................................................................................... 2053
Volume .........................................................................................................................
Indicators 2054
CiAD ................................................................................................................ 2055
Applied ........................................................................................................... 2056
Create ........................................................................................................... 2057
Main ........................................................................................................... 2058
Type ........................................................................................................... 2059
CiMFI ................................................................................................................ 2060
MaPeriod ........................................................................................................... 2061
Applied ........................................................................................................... 2062
Create ........................................................................................................... 2063
Main ........................................................................................................... 2064
Type ........................................................................................................... 2065
CiOBV ................................................................................................................ 2066
Applied ........................................................................................................... 2067
Create ........................................................................................................... 2068
Main ........................................................................................................... 2069
Type ........................................................................................................... 2070
CiVolumes ................................................................................................................ 2071
............................................................................................................................2130
Trade Classes
CAccountInfo
......................................................................................................................... 2131
Login ................................................................................................................ 2133
TradeMode................................................................................................................ 2134
TradeModeDescription
................................................................................................................ 2135
Leverage ................................................................................................................ 2136
MarginMode ................................................................................................................ 2137
MarginModeDescription
................................................................................................................ 2138
TradeAllowed ................................................................................................................ 2139
TradeExpert ................................................................................................................ 2140
LimitOrders ................................................................................................................ 2141
Balance ................................................................................................................ 2142
Credit ................................................................................................................ 2143
Profit ................................................................................................................ 2144
Equity ................................................................................................................ 2145
Margin ................................................................................................................ 2146
FreeMargin................................................................................................................ 2147
MarginLevel ................................................................................................................ 2148
MarginCall ................................................................................................................ 2149
MarginStopOut................................................................................................................ 2150
Name ................................................................................................................ 2151
Server ................................................................................................................ 2152
Currency ................................................................................................................ 2153
Company ................................................................................................................ 2154
InfoInteger................................................................................................................ 2155
InfoDouble ................................................................................................................ 2156
InfoString ................................................................................................................ 2157
OrderProfitCheck
................................................................................................................ 2158
MarginCheck ................................................................................................................ 2159
FreeMarginCheck
................................................................................................................ 2160
MaxLotCheck ................................................................................................................ 2161
CSymbolInfo
......................................................................................................................... 2162
Refresh ................................................................................................................ 2166
RefreshRates ................................................................................................................ 2167
Name ................................................................................................................ 2168
Select ................................................................................................................ 2169
IsSynchronized
................................................................................................................ 2170
Volume ................................................................................................................ 2171
VolumeHigh................................................................................................................ 2172
VolumeLow................................................................................................................ 2173
VolumeBid ................................................................................................................ 2174
VolumeAsk ................................................................................................................ 2175
Time ................................................................................................................ 2176
Spread ................................................................................................................ 2177
SpreadFloat................................................................................................................ 2178
TickBookDepth................................................................................................................ 2179
StopsLevel................................................................................................................ 2180
FreezeLevel ................................................................................................................ 2181
Bid ................................................................................................................ 2182
BidHigh ................................................................................................................ 2183
BidLow ................................................................................................................ 2184
Ask ................................................................................................................ 2185
AskHigh ................................................................................................................ 2186
AskLow ................................................................................................................ 2187
Last ................................................................................................................ 2188
LastHigh ................................................................................................................ 2189
LastLow ................................................................................................................ 2190
TradeCalcMode................................................................................................................ 2191
TradeCalcModeDescription
................................................................................................................ 2192
TradeMode................................................................................................................ 2193
TradeModeDescription
................................................................................................................ 2194
TradeExecution
................................................................................................................ 2195
TradeExecutionDescription
................................................................................................................ 2196
SwapMode ................................................................................................................ 2197
SwapModeDescription
................................................................................................................ 2198
SwapRollover3days
................................................................................................................ 2199
SwapRollover3daysDescription
................................................................................................................ 2200
MarginInitial................................................................................................................ 2201
MarginMaintenance
................................................................................................................ 2202
MarginLong................................................................................................................ 2203
MarginShort ................................................................................................................ 2204
MarginLimit................................................................................................................ 2205
MarginStop................................................................................................................ 2206
MarginStopLimit
................................................................................................................ 2207
TradeTimeFlags
................................................................................................................ 2208
TradeFillFlags
................................................................................................................ 2209
Digits ................................................................................................................ 2210
Point ................................................................................................................ 2211
TickValue ................................................................................................................ 2212
TickValueProfit
................................................................................................................ 2213
TickValueLoss................................................................................................................ 2214
TickSize ................................................................................................................ 2215
ContractSize ................................................................................................................ 2216
LotsMin ................................................................................................................ 2217
LotsMax ................................................................................................................ 2218
LotsStep ................................................................................................................ 2219
LotsLimit ................................................................................................................ 2220
SwapLong ................................................................................................................ 2221
SwapShort ................................................................................................................ 2222
CurrencyBase ................................................................................................................ 2223
CurrencyProfit
................................................................................................................ 2224
CurrencyMargin
................................................................................................................ 2225
Bank ................................................................................................................ 2226
Description................................................................................................................ 2227
Path ................................................................................................................ 2228
InfoInteger................................................................................................................ 2229
InfoDouble ................................................................................................................ 2230
InfoString ................................................................................................................ 2231
NormalizePrice
................................................................................................................ 2232
COrderInfo
......................................................................................................................... 2233
Ticket ................................................................................................................ 2235
TimeSetup ................................................................................................................ 2236
OrderType................................................................................................................ 2237
TypeDescription
................................................................................................................ 2238
State ................................................................................................................ 2239
StateDescription
................................................................................................................ 2240
TimeExpiration
................................................................................................................ 2241
TimeDone ................................................................................................................ 2242
TypeFilling ................................................................................................................ 2243
TypeFillingDescription
................................................................................................................ 2244
TypeTime ................................................................................................................ 2245
TypeTimeDescription
................................................................................................................ 2246
Magic ................................................................................................................ 2247
PositionId ................................................................................................................ 2248
VolumeInitial................................................................................................................ 2249
VolumeCurrent................................................................................................................ 2250
RequestTypeFilling
................................................................................................................ 2374
RequestTypeFillingDescription
................................................................................................................ 2375
RequestTypeTime
................................................................................................................ 2376
RequestTypeTimeDescription
................................................................................................................ 2377
RequestExpiration
................................................................................................................ 2378
RequestComment
................................................................................................................ 2379
Result ................................................................................................................ 2380
ResultRetcode................................................................................................................ 2381
ResultRetcodeDescription
................................................................................................................ 2382
ResultDeal ................................................................................................................ 2383
ResultOrder ................................................................................................................ 2384
ResultVolume ................................................................................................................ 2385
ResultPrice................................................................................................................ 2386
ResultBid ................................................................................................................ 2387
ResultAsk ................................................................................................................ 2388
ResultComment................................................................................................................ 2389
CheckResult ................................................................................................................ 2390
CheckResultRetcode
................................................................................................................ 2391
CheckResultRetcodeDescription
................................................................................................................ 2392
CheckResultBalance
................................................................................................................ 2393
CheckResultEquity
................................................................................................................ 2394
CheckResultProfit
................................................................................................................ 2395
CheckResultMargin
................................................................................................................ 2396
CheckResultMarginFree
................................................................................................................ 2397
CheckResultMarginLevel
................................................................................................................ 2398
CheckResultComment
................................................................................................................ 2399
PrintRequest ................................................................................................................ 2400
PrintResult................................................................................................................ 2401
FormatRequest................................................................................................................ 2402
FormatRequestResult
................................................................................................................ 2403
............................................................................................................................2404
Trading Strategy Classes
Base classes
.........................................................................................................................
for Expert Advisors 2407
CExpert ................................................................................................................ 2408
Init ........................................................................................................... 2412
InitSignal ........................................................................................................... 2413
InitTrailing........................................................................................................... 2414
InitMoney ........................................................................................................... 2415
Deinit ........................................................................................................... 2416
MaxOrders........................................................................................................... 2417
OnTick ........................................................................................................... 2418
OnTrade ........................................................................................................... 2419
OnTimer ........................................................................................................... 2420
InitParameters
........................................................................................................... 2421
InitIndicators
........................................................................................................... 2422
InitTrade ........................................................................................................... 2423
DeinitTrade ........................................................................................................... 2424
DeinitSignal ........................................................................................................... 2425
DeinitTrailing
........................................................................................................... 2426
DeinitMoney ........................................................................................................... 2427
DeinitIndicators
........................................................................................................... 2428
Refresh ........................................................................................................... 2429
Processing........................................................................................................... 2430
CheckOpen........................................................................................................... 2432
CheckOpenLong........................................................................................................... 2433
CheckOpenShort
........................................................................................................... 2434
OpenLong ........................................................................................................... 2435
OpenShort........................................................................................................... 2436
CheckClose........................................................................................................... 2437
CheckCloseLong
........................................................................................................... 2439
CheckCloseShort
........................................................................................................... 2440
CloseAll ........................................................................................................... 2441
Close ........................................................................................................... 2442
CloseLong ........................................................................................................... 2443
CloseShort........................................................................................................... 2444
CheckReverse........................................................................................................... 2445
CheckReverseLong
........................................................................................................... 2446
CheckReverseShort
........................................................................................................... 2447
ReverseLong ........................................................................................................... 2448
ReverseShort........................................................................................................... 2449
CheckTrailingStop
........................................................................................................... 2450
CheckTrailingStopLong
........................................................................................................... 2451
CheckTrailingStopShort
........................................................................................................... 2452
TrailingStopLong
........................................................................................................... 2453
TrailingStopShort
........................................................................................................... 2454
CheckTrailingOrderLong
........................................................................................................... 2455
CheckTrailingOrderShort
........................................................................................................... 2456
TrailingOrderLong
........................................................................................................... 2457
TrailingOrderShort
........................................................................................................... 2458
CheckDeleteOrderLong
........................................................................................................... 2459
CheckDeleteOrderShort
........................................................................................................... 2460
DeleteOrders........................................................................................................... 2461
DeleteOrder ........................................................................................................... 2462
DeleteOrderLong
........................................................................................................... 2463
DeleteOrderShort
........................................................................................................... 2464
LotOpenLong ........................................................................................................... 2465
LotOpenShort........................................................................................................... 2466
LotReverse........................................................................................................... 2467
PrepareHistoryDate
........................................................................................................... 2468
HistoryPoint........................................................................................................... 2469
CheckTradeState
........................................................................................................... 2470
WaitEvent........................................................................................................... 2471
NoWaitEvent ........................................................................................................... 2472
IsWaitingPositionOpened
........................................................................................................... 2473
IsWaitingPositionVolumeChanged
........................................................................................................... 2474
IsWaitingPositionModified
........................................................................................................... 2475
IsWaitingPositionClosed
........................................................................................................... 2476
IsWaitingPositionStopTake
........................................................................................................... 2477
IsWaitingOrderPlaced
........................................................................................................... 2478
IsWaitingOrderModified
........................................................................................................... 2479
IsWaitingOrderDeleted
........................................................................................................... 2480
IsWaitingOrderTriggered
........................................................................................................... 2481
TradeEventPositionStopTake
........................................................................................................... 2482
TradeEventOrderTriggered
........................................................................................................... 2483
TradeEventPositionOpened
........................................................................................................... 2484
TradeEventPositionVolumeChanged
........................................................................................................... 2485
TradeEventPositionModified
........................................................................................................... 2486
TradeEventPositionClosed
........................................................................................................... 2487
TradeEventOrderPlaced
........................................................................................................... 2488
TradeEventOrderModified
........................................................................................................... 2489
TradeEventOrderDeleted
........................................................................................................... 2490
TradeEventNotIdentified
........................................................................................................... 2491
TimeframeAdd........................................................................................................... 2492
TimeframesFlags
........................................................................................................... 2493
CExpertSignal
................................................................................................................ 2494
Init ........................................................................................................... 2495
InitIndicators
........................................................................................................... 2496
ValidationSettings
........................................................................................................... 2497
CheckOpenLong........................................................................................................... 2498
CheckCloseLong
........................................................................................................... 2499
CheckOpenShort
........................................................................................................... 2500
CheckCloseShort
........................................................................................................... 2501
CheckReverseLong
........................................................................................................... 2502
CheckReverseShort
........................................................................................................... 2503
CheckTrailingOrderLong
........................................................................................................... 2504
CheckTrailingOrderShort
........................................................................................................... 2505
CExpertTrailing
................................................................................................................ 2506
Init ........................................................................................................... 2507
InitIndicators
........................................................................................................... 2508
ValidationSettings
........................................................................................................... 2509
CheckTrailingStopLong
........................................................................................................... 2510
CheckTrailingStopShort
........................................................................................................... 2511
CExpertMoney ................................................................................................................ 2512
Percent ........................................................................................................... 2513
Init ........................................................................................................... 2514
InitIndicators
........................................................................................................... 2515
ValidationSettings
........................................................................................................... 2516
CheckOpenLong........................................................................................................... 2517
CheckOpenShort
........................................................................................................... 2518
CheckReverse ........................................................................................................... 2519
CheckClose........................................................................................................... 2520
Modules.........................................................................................................................
of Trade Signals 2521
Signals of the................................................................................................................
Indicator Accelerator Oscillator 2524
Signals of the................................................................................................................
Indicator Adaptive Moving Average 2527
Signals of the................................................................................................................
Indicator Awesome Oscillator 2529
Signals of the................................................................................................................
Oscillator Bears Power 2533
Signals of the................................................................................................................
Oscillator Bulls Power 2535
Signals of the................................................................................................................
Oscillator Commodity Channel Index 2537
Signals of the................................................................................................................
Oscillator DeMarker 2541
Signals of the................................................................................................................
Indicator Double Exponential Moving Average 2545
Signals of the................................................................................................................
Indicator Envelopes 2547
Signals of the................................................................................................................
Indicator Fractal Adaptive Moving Average 2550
Signals of the................................................................................................................
Intraday Time Filter 2552
Signals of the................................................................................................................
Oscillator MACD 2554
Signals of the................................................................................................................
Indicator Moving Average 2560
Signals of the................................................................................................................
Indicator Parabolic SAR 2562
Signals of the................................................................................................................
Oscillator Relative Strength Index 2564
Signals of the................................................................................................................
Oscillator Relative Vigor Index 2570
Signals of the................................................................................................................
Oscillator Stochastic 2572
Signals of the................................................................................................................
Oscillator Triple Exponential Average 2577
Signals of the................................................................................................................
Indicator Triple Exponential Moving Average 2581
Signals of the................................................................................................................
Oscillator Williams Percent Range 2583
Trailing.........................................................................................................................
Stop Classes 2586
CTrailingFixedPips
................................................................................................................ 2587
StopLevel ........................................................................................................... 2588
ProfitLevel........................................................................................................... 2589
ValidationSettings
........................................................................................................... 2590
CheckTrailingStopLong
........................................................................................................... 2591
CheckTrailingStopShort
........................................................................................................... 2592
CTrailingMA................................................................................................................ 2593
Period ........................................................................................................... 2594
Shift ........................................................................................................... 2595
Method ........................................................................................................... 2596
Applied ........................................................................................................... 2597
InitIndicators
........................................................................................................... 2598
ValidationSettings
........................................................................................................... 2599
CheckTrailingStopLong
........................................................................................................... 2600
CheckTrailingStopShort
........................................................................................................... 2601
CTrailingNone
................................................................................................................ 2602
CheckTrailingStopLong
........................................................................................................... 2603
CheckTrailingStopShort
........................................................................................................... 2604
CTrailingPSAR
................................................................................................................ 2605
Step ........................................................................................................... 2606
Maximum ........................................................................................................... 2607
InitIndicators
........................................................................................................... 2608
CheckTrailingStopLong
........................................................................................................... 2609
CheckTrailingStopShort
........................................................................................................... 2610
Money Management
.........................................................................................................................
Classes 2611
CMoneyFixedLot
................................................................................................................ 2612
Lots ........................................................................................................... 2613
ValidationSettings
........................................................................................................... 2614
CheckOpenLong........................................................................................................... 2615
CheckOpenShort
........................................................................................................... 2616
CMoneyFixedMargin
................................................................................................................ 2617
CheckOpenLong........................................................................................................... 2618
CheckOpenShort
........................................................................................................... 2619
CMoneyFixedRisk
................................................................................................................ 2620
CheckOpenLong........................................................................................................... 2621
CheckOpenShort
........................................................................................................... 2622
CMoneyNone ................................................................................................................ 2623
ValidationSettings
........................................................................................................... 2624
CheckOpenLong........................................................................................................... 2625
CheckOpenShort
........................................................................................................... 2626
CMoneySizeOptimized
................................................................................................................ 2627
DecreaseFactor
........................................................................................................... 2628
ValidationSettings
........................................................................................................... 2629
CheckOpenLong........................................................................................................... 2630
CheckOpenShort
........................................................................................................... 2631
24 Moving from .................................................................................................
MQL4 2632
MQL5 Reference
MetaQuotes Language 5 (MQL5) is a built-in language for programming trading strategies. This
language is developed by MetaQuotes Software Corp. based on their long experience in the creation of
online trading platforms. Using this language, you can create your own Expert Advisors that make
trading management automated and are perfectly suitable for implementing your own trading
strategies. Besides, using MQL5 you can create your own technical indicators (custom indicators),
scripts and libraries.
MQL5 contains a large number of functions necessary for analyzing current and previously received
quotes, and has built-in basic indicators and functions for managing trade positions and controlling
them.
The MetaEditor 5 (text editor) that highlights different constructions of MQL5 language is used for
writing the program code. It helps users to orientate themselves in the expert system text quite
easily. MetaQuotes Language Dictionary is used as a Help System for MQL5 language.
The brief guide contains functions, operations, reserved words, and other language constructions
divided into categories, and allows finding the description of every used element of the language.
Expert Advisor is a mechanical trading system linked up to a certain chart. An Expert Advisor starts
to run when an event happens that can be handled by it: events of initialization and deinitialization,
event of a new tick receipt, a timer event, depth of market changing event, chart event and custom
events.
An Expert Advisor can both inform you about a possibility to trade and automatically trade on an
account sending orders directly to a trade server. Expert Advisors are stored in
terminal_directory\MQL5\Experts.
Custom Indicator is a technical indicator written independently in addition to those already
integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are
intended for implementing of analytical functions only.
Custom indicators are stored in terminal_directory\MQL5\Indicators
Script is a program intended for a single execution of some actions. Unlike Expert Advisors, scripts
do not process any actions, except for the start event (this requires the OnStart handler function in
a script). Scripts are stored in terminal_directory\MQL5\Scripts
Library is a set of custom functions intended for storing and distributing frequently used blocks of
custom programs. Libraries cannot start executing by themselves.
Libraries are stored in terminal_directory\MQL5\Libraries
Include File is a source text of the most frequently used blocks of custom programs. Such files can
be included into the source texts of Expert Advisors, scripts, custom indicators, and libraries at the
compiling stage. The use of included files is more preferable than the use of libraries because of
additional burden occurring at calling library functions.
Include files can be stored in the same directory as a source file - in this case the #include directive
with double quotes is used. Another place to store include files is terminal_directory\MQL5\Include,
in this case the #include directive is used with angle brackets.
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:
Syntax
Data Types
Operations and Expressions
Operators
Functions
Variables
Preprocessor
Object-Oriented Programming
Syntax
As to 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;
constructors of classes and structures can't have parameters;
no multiple inheritance.
See also
Enumerations, Structures and Classes, Inheritance
Comments
Multi-line comments start with the /* pair of symbols and end with the */ one. Such kind of comments
cannot be nested. Single-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 ti 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.
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
public virtual
Memory Classes
Operators
break do return
default if while
delete new
Other
this #import
true #include
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 complicity
of internal presentation of data with floating point, they are processed slower than the integer ones.
String data are processed at the longest because of dynamic computer memory allocation/reallocation.
structures;
classes.
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. Some 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 types
conversion.
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
Data Conversion, Constants of Numeric Types
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.Since the short type is a sign 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;
Since the unsigned integer types are not designed for storing negative values, the attempt to set a
negative value can lead to unexpected consequences. Such a simple script will lead to an infinite loop:
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:
Hexadecimal: numbers 0-9, the letters a-f or A-F for the values of 10-15; start with 0x or 0x.
Examples:
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 ASCII 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. Some 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='©'; // coed 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, th 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 O 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
StringSetCharacter(), StringGetCharacter(), ShortToString(), ShortArrayToString(),
StringToShortArray()
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.
Either date (year , month, day) or time (hours, minutes, seconds), or all together can be omitted.
Values range from 1 January, 1970 to 31 December, 3000.
Examples:
See also
Structure of the Date Type, Date and Time, TimeToString, StringToTime
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 Web-
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.
Examples:
//--- Literals
C'128,128,128' // Gray
C'0x00,0x00,0xFF' // Blue
//color names
clrRed // Red
clrYellow // Yellow
clrBlack // Black
//--- Integral representations
0xFFFFFF // White
16777215 // White
0x008000 // Green
32768 // Green
See also
Web Colors, ColorToString, StringToColor, 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:
Example:
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 - 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
Unlike 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.
Unlike 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.
For example, 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:
Noted that the value of epsilon in the above example can not be less than the predefined constants
DBL_EPSILON.The value of this constant is 2.2204460492503131e-016. The constant corresponding to
the float type is FLT_EPSILON = 1.192092896e-07. The meaning of these values is the following: it is
the lowest value that satisfies the condition 1.0 + DBL_EPSILON! = 1.0 (for numbers of float type 1.0
+ FLT_EPSILON! = 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:
Some 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 MathIsValidNumber(). 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 nonnumber SNaN
s1=s2;
printf("3. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF8000000000000; // smallest nonnumber QNaN
s1=s2;
printf("4. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FFF000000000000; // greatest nonnumber QNaN
s1=s2;
printf("5. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF0000000000000; // Positive infinity 1.#INF and smallest nnonnumber SNaN
s1=s2;
printf("6. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFF0000000000000; // Negative infinity -1.#INF
s1=s2;
printf("7. %f %I64X",s1.d,s2.l);
//---
s2.l=0x8000000000000000; // Negative zero -0.0
s1=s2;
printf("8. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FE0000000000000; // 0.5
s1=s2;
printf("9. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FF0000000000000; // 1.0
s1=s2;
printf("10. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FEFFFFFFFFFFFFF; // Greatest normalized number (MAX_DBL)
s1=s2;
printf("11. %.16e %I64X",s1.d,s2.l);
//---
See also
DoubleToString, NormalizeDouble, Constants of Numeric Types
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:
Длинные константные строки для удобства чтения исходного кода можно разбивать на части без
операции сложения. Эти части при компиляции автоматически соберутся в одну длинную строку:
See also
Conversion Functions, String Functions, FileOpen, FileReadString, FileWriteString
Structure Declaration
struct structure_name
{
elements_description
};
The structure name can's 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
};
Such 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 double 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
Structures that do not contain strings or objects of dynamic arrays are called simple structures;
variables of such structures can be freely copied to each other, even if they are different structures.
Variables of simple structures, as well as their array can be passed as parameters to functions
The structure is a new type of data allowing to 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;
Classes
Classes differ from structures in the following:
Classes and structures can have an explicit constructor and destructor. If you a 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};
Конструктор - это специальная функция, которая вызывается автоматически при создании объекта
структуры или класса и обычно используется для инициализации членов класса. Далее мы будем
говорить только о классах, при этом все сказанное относится и к структурам, если не оговорено
иное. Имя конструктора должно совпадать с именем класса. Конструктор не имеет
возвращаемого типа (можно указать тип void).
//+------------------------------------------------------------------+
//| класс для работы с датой |
//+------------------------------------------------------------------+
class MyDateClass
{
private:
int m_year; // год
int m_month; // месяц
int m_day; // день месяца
int m_hour; // час в сутках
int m_minute; // минуты
int m_second; // секунды
public:
//--- конструктор по умолчанию
MyDateClass(void);
//--- конструктор с параметрами
MyDateClass(int h,int m,int s);
};
Конструктор можно объявить в описании класса, а затем определить его тело. Например, вот так
могут быть определены два конструктора класса MyDateClass:
//+------------------------------------------------------------------+
//| конструктор по умолчанию |
//+------------------------------------------------------------------+
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__);
}
//+------------------------------------------------------------------+
//| конструктор с параметрами |
//+------------------------------------------------------------------+
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__);
}
//+------------------------------------------------------------------+
//| класс с конструктором по умолчанию |
//+------------------------------------------------------------------+
class CFoo
{
datetime m_call_time; // время последнего обращения к объекту
public:
//--- конструктор с параметром, имюещем значение по умолчанию, не является конструктором по умол
CFoo(datetime t=0){m_call_time=t;};
string ToString(){return(TimeToString(m_call_time,TIME_DATE|TIME_SECONDS));};
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CFoo foo; // такой вариант использовать можно - будет вызван конструктор с параметрами по умолча
или
//+------------------------------------------------------------------+
//| класс без конструктора по умолчанию |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:
В данном примере класс CFoo имеет объявленный параметрический конструктор – в таких случаях
компилятор при компиляции не создает автоматически конструктор по умолчанию. В то же время
при объявлении массива объектов предполагается, что все объекты должны быть созданы и
инициализированы автоматически. При автоматической инициализации объекта требуется вызвать
конструктор по умолчанию, но так как конструктор по умолчанию явно не объявлен и не
сгенерирован автоматически компилятором, то создание такого объекта невозможно. Именно по
этой причине компилятор выдает ошибку еще на этапе компиляции.
Список инициализации – это список инициализаторов, разделенных запятыми, который идет после
двоеточия за списком параметров конструктора и предшествует телу (идет перед открывающей
фигурной скобкой). Есть несколько требований:
//+------------------------------------------------------------------+
//| класс для хранения фамилии и имени персонажа |
//+------------------------------------------------------------------+
class CPerson
{
string m_first_name; // имя
string m_second_name; // фамилия
public:
//--- пустой конструктор по умолчанию
CPerson() {Print(__FUNCTION__);};
//--- параметрический конструктор
CPerson(string full_name);
//--- конструктор со списком инициализации
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()
{
//--- получим ошибку "default constructor is not defined"
CPerson people[5];
CPerson Tom="Tom Sawyer"; // Том Сойер
CPerson Huck("Huckleberry","Finn"); // Гекльберри Финн
CPerson *Pooh = new CPerson("Whinnie","Pooh"); // Винни Пух
//--- выведем значения
Tom.PrintName();
Huck.PrintName();
Pooh.PrintName();
В списке инициализации члены могут идти в любом порядке, но при этом все члены класса будут
инициализироваться согласно порядку их объявления. Это означает, что в третьем конструкторе
сначала будет инициализирован член m_first_name, так как он объявлен первым, и только после
него будет инициализирован член m_second_name. Это необходимо учитывать в тех случаях,
когда инициализация одних членов класса зависит от значений в других членах класса.
Если в базовом классе не объявлен конструктор по умолчанию и при этом объявлен один или
несколько конструкторов с параметрами, то нужно обязательно вызвать один из конструкторов
базового класса в списке инициализации. Он идет через запятую как обычные члены списка и
будет вызван в первую очередь при инициализации объекта независимо от местоположения в
списке инициализации.
//+------------------------------------------------------------------+
//| базовый класс |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:
//--- конструктор со списком инициализации
CFoo(string name) : m_name(name) { Print(m_name);}
};
//+------------------------------------------------------------------+
//| потомок класса CFoo |
//+------------------------------------------------------------------+
class CBar : CFoo
{
CFoo m_member; // член класса является объектом предка
public:
//--- конструктор по умолчанию в списке инициализации вызывает конструктор предка
CBar(): m_member(_Symbol), CFoo("CBAR") {Print(__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CBar bar;
}
В приведенном примере при создании объекта bar будет вызван конструктор по умолчанию CBar(),
в котором сначала вызывается конструктор для предка CFoo, а затем конструктор для члена
класса m_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 (~). Strings, 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 with SetRightBorder(int border) on the Draw() are declared and defined directly inside the
CTetrisShape class.
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);
}
When developing a new class, it is recommended to restrict access to the members from the outside.
For these purposes keywords 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 DOM
int m_rows[FIELD_HEIGHT]; // Numbering of the DOM 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 CTetrisField(), 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. Specifiers of access to
elements always end with a colon (:) and can appear in the class definition many times.
Access to the members of the basis class can be redefined during inheritance in derived classes.
See also
Object-Oriented Programming
A dynamic array is a 40-byte large structure. Maximum 4-dimension array can be declared.
struct MqlArrayObject
{
ushort type; // Encoded data type
ushort flags; // Flags that determine the status of the array
uint item_len; // Size of one element of the array in bytes
int allocated; // Actual size, allocated for the array
int range0; // Size of the first dimension (initially equal to 0)
int range1; // Size of the second dimension, if any. Otherwise 0
int range2; // Size of the third dimension, if any. Otherwise 0
int range3; // Size of the fourth dimension, if any. Otherwise 0
int reserved0; // Data for
int reserved1; // Internal
int reserved2; // Usage
};
When declaring a dynamic array (an array of unspecified value in the first pair of square brackets),
the compiler automatically creates a variable of the above structure (a dynamic array object) and
provides 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
When all significant array dimensions are explicitly specified, the compiler pre-allocates the necessary
memory size. Such an array is called static. Nevertheless, the compiler allocates additional memory
for the object of a dynamic array, which (object) is associated with 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:
...
return(true);
}
Arrays in Structures
When 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 Windows API.
However, 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, connected
with the static array - structure member, will be created.
See also
Array Functions, Initialization of Variables, Visibility Scope 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:
Solid lines 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 functional recording
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
Before operations (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
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));
Data of the simple structures type can be assigned to each other only if all the members of both
structures are of numeric types. In this case both operands of the assignment operation (left and
right) must be of the structures type. The member-wise casting is not performed, a simple copying is
done. If the structures are of different sizes, the number of bytes of the smaller size is copied. Thus
the absence of union in MQL5 is compensated.
Examples:
struct str1
{
double d;
};
//---
struct str2
{
long l;
};
//---
struct str3
{
int low_part;
int high_part;
};
//---
struct str4
{
string s;
};
//+------------------------------------------------------------------+
void OnStart()
{
str1 s1;
str2 s2;
str3 s3;
str4 s4;
//---
s1.d=MathArcsin(2.0); // get the invalid number -1. # IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s3=s2;
printf("2. high part of long %.8X low part of long %.8X",
s3.high_part,s3.low_part);
//---
s4.s="some constant string";
s3=s4;
printf("3. buffer len is %d constant string address is 0x%.8X",
s3.low_part,s3.high_part);
}
Another example illustrates the method of organizing a custom function for receiving RGB (Red,
Green, Blue) representation from the color type. Create two structures of the same size but with
different contents. For convenience, let's add a function returning the RGB representation of a color
as a string.
#property script_show_inputs
input color testColor=clrBlue;// set color for testing
//--- structure for representing color as RGB
struct RGB
{
uchar blue; // blue component of color
uchar green; // green component of color
uchar red; // red component of color
uchar empty; // this byte is not used
string toString(); // function for receiving a string
};
//--- function for showing color as a string
string RGB::toString(void)
{
string out="("+(string)red+":"+(string)green+":"+(string)blue+")";
return out;
}
//--- structure for storing of the built-in color type
struct builtColor
{
color c;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- a variable for storing in RGB
RGB colorRGB;
//--- variable for storing the color type
builtColor test;
test.c=testColor;
//--- casting two structures by copying contents
colorRGB=test;
Print("color ",test.c,"=",colorRGB.toString());
//---
}
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.
See also
Data Types
The predefined constant variable NULL is of the void type. It can be assigned to variables of any other
fundamental types without conversion. The comparison of fundamental type variables with the NULL
value is allowed.
Example:
//--- If the string is not initialized, then assign our predefined value to it
if(some_string==NULL) some_string="empty";
Also NULL can be compared to pointers to objects created with the new operator.
See also
Variables, Functions
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. Syntactically,
object descriptors in MQL5 are similar to pointers in C++.
Examples:
Again, unlike C++, the variable hobject from the example above is not a pointer to the memory, it is
a descriptor of the object.
See also
Variables, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and
Deleting Objects
Passing a parameter by reference means passing the address of the variable, that's why all changes in
the parameter that is passed by reference will be immediately reflected in the source variable. Using
parameter passing by reference, you can implement return of several results of a function at the same
time. In order to prevent changing of a parameter passed by reference, use the const modifier.
Thus, if the input parameter of a function is an array, a structure or class object, symbol '&' is placed
in the function header after the variable type and before its name.
Example
class CDemoClass
{
private:
double m_array[];
public:
void setArray(double &array[]);
};
//+------------------------------------------------------------------+
//| filling the array |
//+------------------------------------------------------------------+
void CDemoClass::setArray(double &array[])
{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array, array);
}
}
In the above example class CDemoClass is declared, which contains the private member - array
m_array[] of double type. Function setArray() is declared, to which array[] is passed by reference. If
the function header doesn't contain the indication about passing by reference, i.e. doesn't contain the
ampersand character, an error message will be generated at the attempt to compile such a code.
Despite the fact that the array is passed by reference, we can't assign one array to another. We 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));
}
Structures don't have pointers, operators new and delete can't be applied to them, not GetPointer
(this) can be used.
See also
Object Pointers, Creating and Deleting Objects, Visibility Scope and Lifetime of Variables
Operation symbols are used in expressions and have sense when appropriate operands are given
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.
Expressions
Arithmetical 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:
See also
Precedence Rules
Arithmetic Operations
Arithmetical 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;
Divisions reminder 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.
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:
The following operations unite arithmetic or bitwise operations with operation of assignment:
Bitwise operations can be applied to integers only. When 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 FALSE 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 FALSE (0) or TRUE
(1).
True if a is equal to b a == b;
True if a is not equal to b a != b;
True if a is less than b a < b;
True if a is greater than b a > b;
True if a is less than or equal to b a <= b;
True if a is greater than or equal to b a >= b;
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).
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).
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");
}
}
//+------------------------------------------------------------------+
//| the function always returns false |
//+------------------------------------------------------------------+
bool func_false()
{
Print("Function func_false()");
return(false);
}
//+------------------------------------------------------------------+
//| the function always returns true |
//+------------------------------------------------------------------+
bool func_true()
{
Print("Function func_true()");
return(true);
}
See also
Precedence Rules
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.
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:
See also
Precedence Rules
Other operations
Indexing ( [] )
When 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
measurement is indexed from 0 to measurement size-1. In particular case, for a one-dimensional
array consisting of 50 elements, the reference to the first element will look like array [0], that to the
last element will be array [49].
When addressing beyond the array, the executing subsystem will generate a critical error, and the
program will be stopped.
The expression value is the value returned by the function. If the return value is of void type, such
function call cannot be placed to the right in the assignment operation. Please make sure that the
expressions x1,..., Xn are executed exactly in this order.
Example:
int length=1000000;
string a="a",b="b",c;
//---
int start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c = a + b' = ",(stop-start)," milliseconds, i = ",i);
Comma Operation ( , )
Expressions separated by commas are 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 usesd.
Syntax:
Variable_name_of_structure_type.Member_name
Example:
struct SessionTime
{
string sessionName;
int startHour;
int startMinutes;
int endHour;
int endMinutes;
} st;
st.sessionName="Asian";
st.startHour=0;
st.startMinutes=0;
st.endHour=9;
st.endMinutes=0;
[Scope_name]::Function_name(parameters)
If there is no scope name, this is the explicit direction to use the global scope. If there is no scope
resolution operation, the function is sought in the nearest scope. If there is no function n the local
scope, the search is conducted in the global scope.
type Calss_name::Function_name(parameters_description)
{
// function body
}
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();
}
//+------------------------------------------------------------------+
Example:
sizeof(expression)
Any identifier, or type name enclosed in brackets can be used as an expression. Note that the void
type name can't be used, and the identifier cannot belong to the field of bits, or be a function name.
If the expression is the name of a static array (i.e. the first dimension is given), then the result is the
size of the whole array (i.e. the product of the number of elements the the type length). 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.
When 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));
See also
Precedence Rules
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
task. The program body is a sequence of such operators. Operators following one by one are separated
by semicolons.
Operator Description
Expression operator (;) Any expression that ends with a semicolon (;)
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.
Example:
if(Month() == 12)
See also
Initialization of Variables, Visibility Scope 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 Scope 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 left to right:
FileClose(file);
Empty Operator
Consists only of a semicolon (;) and is used to denote an empty body of a control operator.
See also
Initialization of Variables, Visibility Scope 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.
What can be returned: simple types, simple structures, object pointers. With the return operator you
can't return any arrays, class objects, variables of compound structure type.
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
if (expression)
operator1
else
operator2
If the expression is true, operator1 is executed and control is given to the operator that follows
operator2 (operator2 is not executed). If the expression is false, operator2 is executed.
The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators
with omitted else part. In this case, else addresses to the nearest previous if operator in the same
block that has no else part.
Examples:
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
?: conditional 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);
double true_range;
if(High==Low)true_range=0; // if High and Low are equal
else true_range=(Close-Open)/(High-Low); // if the range is not null
Note
Be careful when using the conditional operator as an argument of an overloaded function, because the
type of the result of a conditional operator is defined at the time of program compilation. An this type
is defined 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
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
Switch Operator
It compares the expression value with constants in all variants of case and gives 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's contain variables
or function calls. Expression of the switch operator must be of integer type.
switch(expression)
{
case constant: operators
case constant: operators
...
default: operators
}
Operators connected with the default label are executed if none of the constants in case operators
equals to the expression value. The default variant should not necessarily be announced and should
not necessarily be 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 keyword case and the constant are just labels, and if operators are executed for some case
variant, the program will further execute the operators of all following variants until the break
operator occurs. It makes it possible to bind a subsequence of operators with several variants.
A constant expression is calculated during compilation. No two constants in one switch operator can
have the same 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 Scope and Lifetime of Variables, Creating and Deleting Objects
while(expression)
operator;
If the expression is true, the operator is executed until the expression becomes false. If the
expression is false, the control is passed to the next operator. The expression value is defined before
the operator is executed. Therefore, if the expression is false from the very beginning, the operator
will not be executed at all.
Note
If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the IsStopped() function.
Example:
See also
Initialization of Variables, Visibility Scope 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 becomes false.
If it is false, the loop is terminated, and control is transferred to the next operator. Expression3 is
calculated after each iteration.
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 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 IsStopped() 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 Scope and Lifetime of Variables, Creating and Deleting Objects
do
operator;
while(expression)
First the 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 IsStopped() function.
Example:
See also
Initialization of Variables, Visibility Scope 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 us assigned to a
variable.
Example:
See also
Initialization of Variables, Visibility Scope 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 Scope and Lifetime of Variables, Creating and Deleting Objects
The new operator can be applied only to class objects. They can't be applied to structures.
The operator shall not be used to create arrays of objects. To do this, use ArrayResize().
Example:
//+------------------------------------------------------------------+
//| Figure creation |
//+------------------------------------------------------------------+
void CTetrisField::NewShape()
{
m_ypos=HORZ_BORDER;
//--- randomly create one of the 7 possible shapes
int nshape=rand()%7;
switch(nshape)
{
case 0: m_shape=new CTetrisShape1; break;
case 1: m_shape=new CTetrisShape2; break;
case 2: m_shape=new CTetrisShape3; break;
case 3: m_shape=new CTetrisShape4; break;
case 4: m_shape=new CTetrisShape5; break;
case 5: m_shape=new CTetrisShape6; break;
case 6: m_shape=new CTetrisShape7; break;
}
//--- draw
if(m_shape!=NULL)
{
//--- pre-settings
m_shape.SetRightBorder(WIDTH_IN_PIXELS+VERT_BORDER);
m_shape.SetYPos(m_ypos);
m_shape.SetXPos(VERT_BORDER+SHAPE_SIZE*8);
//--- draw
m_shape.Draw();
}
//---
}
It should be noted that the object descriptor not a pointer to the memory.
The object created with the new operator must be explicitly removed by the delete operator.
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
Example:
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
Functions
Every task can be divided into subtasks, each of which can either be directly represented in the form
of a code, or divided into smaller sub-tasks. This method is called stepwise refinement. Functions are
used for writing the code of sub-tasks 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. 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.
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.
Arguments (formal parameters) are passed by value, i.e. each expression xl,..., Xn is calculated, and
the value is passed to the function. The order of expressions calculation and that of values loading are
guaranteed. During the execution, the system checks the number and type of arguments passed to the
function. Such 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:
When calling a function, one may not skip parameters, even those having default values:
somefunc(3.14, , 10); // Wrong call -> the second parameter was skipped.
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 and structure type variables (class objects) are
always passed by reference. In order to exclude changes in actual parameters (arguments passed at
function call) use the access specifier const. When 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 braces.
Example:
void OnStart()
{
//---
int a[]={0,1,2};
int i=0;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void func(int par1,int par2,string comment)
{
At first call in the mentioned example the i variable first takes part in the concatenation of strings
Here its value doesn't change. The i variable takes part in the calculation of the a[i++] array element,
i.e. after the i element of the array is taken, the i variable is incremented. And only after that the
first parameter with the changed value of i variable is calculated.
At the second call when calculating all three parameters, one and the same value of i is used, the one
that was calculated on the first phase of function calling, and only after the first parameters is
calculated the i variable is changed again.
See also
Visibility Scope 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. Sometimes 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]; // Addition to 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]; // Addition to the double
}
aver=(double)sum/size;// Give the amount of type double, and divide
//---
Print("Calculation of the average for an array of int type");
return aver;
}
Each function contains the message output via the Print() function;
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
Overloading is the practice of assigning multiple values to a function. Selecting a specific value
depends on the types of arguments received by the function. A specific function is selected based on
the correspondence of the list of arguments when calling the function, to the list of parameters in the
function declaration.
When an overloaded function is called, the compiler must have an algorithm to select the appropriate
function. The algorithm that performs this choice depends on conversions of what type are present.
The best correlation must be unique. It must be the best for at least one argument, and as well as the
other correspondences for all other arguments.
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. Similar 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.
Examples of overloaded functions in MQL5 can be seen in the example of ArrayInitialize() functions.
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 fmax() in
3 different ways, but only two variants are correct.
Example:
See also
Overload, Virtual Functions, Polymorphism
Examples:
#import "user32.dll"
int MessageBoxW(int hWnd ,string szText,string szCaption,int nType);
int SendMessageW(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex5"
double round(double value);
#import
With the help of 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.
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. Such a function is called exportable, and it can be called from other programs after
compilation.
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
The event handler of the client terminal identifies functions, handling this or that event, by the type
of return value and type of parameters. If other parameters, not corresponding to below descriptions,
are specified for a corresponding function, or another return type is indicated for it, such a function
will not be used as an event handler.
OnStart
The OnStart() function is the Start event handler, which is automatically generated only for running
scripts. It must be of void type, with no parameters:
void OnStart();
For the OnStart() 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 REASON_INITFAILED.
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.
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 a 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 Tick 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 Tick 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
EventSetTimer() 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 EventSetTimer() function once in the OnInit() function, and the
EventKillTimer() function should be called once in OnDeinit().
Every Expert Advisor, as well as every indicator works with its own timer and receives events only
from it. As soon as a 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. When a trade activity is
performed pending order opening, position opening/closing, stops setting, pending order triggering,
etc.) the history of orders and trades 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 OrderSend() 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 the user remembers the ticket
value, during OnTrade() event handling he/she will be able to find out what happened to the order
using this value.
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.
OnBookEvent
The OnBookEvent() function is the BookEvent handler. BookEvent is generated for Expert Advisors
only when Depth of Market changes. It must be of the void type and have one parameter of the string
type:
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 MarketBookRelease().
Unlike 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
The function can be called only in Expert Advisors and indicators. The function should be of void type
with 4 parameters:
For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through this parameters
are listed in the below table.
ID of the user CHARTEVENT_CU Value set by the Value set by the Value set by the
event under the STOM+N EventChartCusto EventChartCusto EventChartCusto
N number m() fubction 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. Within 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 ArrayGetAsSeries(). In order not to
depend on the default values, you must unconditionally call the ArraySetAsSeries() function for those
arrays, that are expected to work with.
The appropriate timeseries or indicator as the price[] array is selected by the user when starting the
indicator in the "Parameters" tab. To do this you must specify the necessary item in the drop-down list
of the "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 nest 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=StatusInfoString(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_PRICE 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 timeseries is used for
calculations.
Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and low prices
and close prices of the current timeframe.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 ArrayGetAsSeries(). In order not to depend on default values, you should
unconditionally call the ArraySetAsSeries() 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 noted 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 DataWindow of the
client terminal.
To understand it better, it would be useful to start the indicator, whose 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(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& time[],
const double& open[],
const double& high[],
const double& low[],
const double& close[],
const long& tick_volume[],
const long& volume[],
const int& spread[])
{
//--- Get the number of bars available for the current 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
Running Programs, Client Terminal Events, Working with Events
Variables
Declaring Variables
Variables must be declared before they are used. Unique names are used to identify variables.
Descriptions of variables are used for them to be defined and for types to be declared. Description is
not an operator.
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';
struct MyTime
{
int hour; // 0-23
int minute; // 0-59
int second; // 0-59
};
...
MyTime strTime; // Variable of the previously declared structure MyTime MyTime
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].
Static arrays can't be represented as timeseries, i.e., the ArraySetAsSeries() 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. The const specifier can't be
applied to members of structures and classes.
Sample
Storage Classes
There are three storage classes: static, input and extern. These modifiers of a storage class explicitly
indicate to the compiler that corresponding variables are distributed in a pre-allocated area of
memory, which is called the global pool. Besides, these modifiers indicate the special processing of
variable data. If a variable declare 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 Scope and
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);
}
Scope of a variable is a program part, in which a variable can 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("In 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.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope 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.
Some 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:
When calling such 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 shown in the calling function in any way. Arrays of any
type and data of the structure type are always passed by reference. If it's necessary to prohibit
modifying the array or structure contents, the parameters of these types must be declared with the
const keyword.
There is an opportunity to pass parameters of simple types by reference. In this case, modification of
such parameters will affect the corresponding variables in the called function 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;
}
See also
Input Variables, Data Types, Encapsulation and Extensibility of Types,Initialization of Variables,
Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
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.
Static 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.
With 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 declare 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 Scope and
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 right after the program is loaded into the client terminal
memory.
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 Scope 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.
Example:
Input variables determine the input parameters of a program. They are available from the Properties
window of a program.
It is possible to set another way to display names of input parameters in the Inputs tab. To do this, a
string comment is used, which should be located after the description of an input parameter in the
same line. Thus, names more understandable for a user can be matched to input parameters.
Example:
Note: Arrays and variables of complex types can't act as input variables.
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 enumerations provided in MQL5, but also user defined variables can be used as input
variables (input parameters for mql5 programs). For example, we can create the dayOfWeek
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
};
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. We start the script and can
choose one of values of the dayOfWeek enumeration from the list. We start the EnumInInput script
and go to the Inputs tab. By default, the value of swapday (day of triple swap charge) is Wednesday
(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. Therefore, in order to select the 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 dayOfWeek 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.
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.
When 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 initializes 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 Scope 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 variables can 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};
List of values of the array elements must be enclosed in curly brackets. Missed initializing sequences
are considered equal to 0. The initializing sequence must have at least one value: this value is
initialized to the first element of the corresponding structure or array, missing elements are
considered equal to zero.
If the size of the initialized array is not specified, it is determined by a compiler, based on the size of
the initialization sequence. Multi-dimensional arrays cannot be initialized by a one-dimensional
sequence (a sequence without additional curly brackets), except for the case, when only one
initializing element is specified (zero, as a rule).
Arrays (including those announced at the local level) can be initialized only by constants.
Examples:
struct str3
{
int low_part;
int high_part;
};
struct str10
{
str3 s3;
double d1[10];
int i3;
};
void OnStart()
{
str10 s10_1={{1,0},{1.0,2.1,3.2,4.4,5.3,6.1,7.8,8.7,9.2,10.0},100};
str10 s10_2={{1,0},{0},100};
str10 s10_3={{1,0},{1.0}};
//---
Print("1. s10_1.d1[5] = ",s10_1.d1[5]);
Print("2. s10_2.d1[5] = ",s10_2.d1[5]);
Print("3. s10_3.d1[5] = ",s10_3.d1[5]);
Print("4. s10_3.d1[0] = ",s10_3.d1[0]);
}
See also
Data Types, Encapsulation and Extensibility of Types, Visibility Scope and Lifetime of Variables,
Creating and Deleting Objects
A variable declared outside all functions is located into the global scope. Access to such variables can
be done from anywhere in the program.These variables are located in the global pool of memory, so
their lifetime coincides with the lifetime of the program.
A variable declared inside a block (part of code enclosed in curly brackets) belongs to the local scope.
Such a variable is not visible (and therefore not available) outside the block, in which it is declared.
The most common case of local declaration is a variable declared within a function. A variable
declared locally, is located on the stack, and the lifetime of such a variable is equal to the lifetime of
the function.
Since the scope of a local variable is the block in which it is declared, it is possible to declare variables
with the same name, as those of variables declared in other blocks; as well as of those declared at
upper levels, up to the global level.
Example:
for(i=limit;i<rates_total;i++)
{
sum=0;
Its scope is only the for cycle; outside of this cycle 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
Despite the fact that static variables are usually declared at a local level, the memory for these
variables is pre-allocated, and initialization is performed right after a program is loaded, the same as
for global variables.
The initialization order corresponds to the variable declaration order in the program. Deinitialization
is performed in the reverse order. This rule is true only for the variables that were not created by the
new operator. Such variables are created and initialized automatically right after loading, and are
deinitialized before the program unloading.
Local variables are deinitialized at the end of the program block, in which they were declared, and in
the order opposite to their declaration. A program block is a compound operator that can be a part of
selection operator switch, cycle operator (for, while, do-while), a function body or a part of the if-else
operator.
Local variables are initialized only at the moment when the program execution meets the variable
declaration. If during the program execution the block, in which the variable is declared, was not
executed, such a variable is not initialized.
Pointers can be declared on a local or global level; and they can be initialized by the empty value of
NULL or by the value of the pointer of the same or inherited type. If the new operator is called for a
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 objects created 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 are created by the new
operator, and are assuredly deleted either by thedelete operator or automatically by the executing
system of MQL5 during the program unloading. The order of declaration of pointers of dynamically
created object does'nt influence the order of their initialization. The order of initialization and
deinitialization is fully controlled by the programmer.
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 in the "Experts" log in the "Experts" log in the "Experts"
journal about the journal about the journal about
attempt to delete an attempt to delete an undeleted dynamically
automatically created automatically created created objects at the
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope 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.
Declare constants
Set program properties
Include files in program text
Import functions
If the # symbol is used in the first line of the program, this line is a preprocessor directive. A
preprocessor directive ends with a line feed character.
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:
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
With the parametric form, all the subsequent found entries of identifier will be replaced by expression
taking into account the actual parameters. For example:
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:
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
See also
Identifiers, Character Constants
The compiler will write declared values in the configuration of the module executed.
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"
#include <file_name>
#include "file_name"
Examples:
#include <WinUser32.mqh>
#include "mylib.mqh"
The preprocessor replaces the line #include <file_name> with the content of the file WinUser32.mqh.
Angle brackets indicate that the WinUser32.mqh file will be taken from the standard directory (usually
it is terminal_installation_directory\MQL5\Include). The current directory is not visible.
If the file name is enclosed in quotation marks, the search is made in the current directory (which
contains the main source file). The standard directory is not visible.
See also
Standard Library, Importing Functions
#import "file_name"
func1 define;
func2 define;
...
funcN define;
#import
Imported functions can have any names. Functions having the same names but from different modules
can be imported at the same time. Imported functions can have names that coincide with the names
of built-in functions. Operation of scope resolution defines which of the functions should be called.
Since the imported functions are 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.
pointers (*);
links 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 "user32.dll"
int MessageBoxW(uint hWnd,string lpText,string lpCaption,uint uType);
#import "stdlib.ex5"
string ErrorDescription(int error_code);
int RGB(int red_value,int green_value,int blue_value);
bool CompareDoubles(double number1,double number2);
string DoubleToStrMorePrecision(double number,int precision);
string IntegerToHexString(int integer_number);
#import "ExpertSample.dll"
int GetIntValue(int);
double GetDoubleValue(double);
string GetStringValue(string);
double GetArrayItemValue(double &arr[],int,int);
bool SetArrayItemValue(double &arr[],int,int,double);
double GetRatesItemValue(double &rates[][6],int,int,int);
#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.
See also
Including Files
Object-Oriented Programming
Object-oriented programming (OOP) is programming primarily focused on data, data and behavior
being inseparably linked. Data and behavior together constitute a class, while objects are class
instances.
OOP considers computation as modeling of behavior. The modeled item is the object represented by
computational abstractions. Suppose 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 squares joined together
by ribs. 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 DOM boundaries, this requirement must also
be modeled. Besides that, filled rows of cubes must be destroyed and earned points must be counted.
Thus, this easy-to-understand game requires the creation of several models - shape model, DOM
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. Strictly speaking, the model of the "shapes" motion in the DOM is not a
data type, but it is the totality of operations with the "shape" data type, using the restrictions of the
"DOM" data type.
Objects are class variables. Object-oriented programming allows you to easily create and use ADT.
Object-oriented programming uses the inheritance mechanism. The advance of the inheritance 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 Shape first; the other
seven classes representing all of the 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 task 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 is well aware of 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. Encapsulation combines, on the one hand, the internal details of the
implementation of a particular type and, on the other hand, 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:
An abstract data type, for example, a string, is a description of the ideal, well known behavior type.
The string user knows that the string operations, such as concatenation or print, have a certain
behavior. Concatenation and print operations are called methods.
A certain implementation of ADT may have some restrictions, for example, strings can be limited in
length. These limitations affect the behavior opened to all. At the same time, internal or private
implementation details do not affect directly the way the user sees the object. For example, the string
is often implemented as an array, while the internal base address of this array and its name are not
essential for the user.
Encapsulation is the ability to hide the implementation details when the open interfaces to user-
defined type is provided. In MQL5, as well as in C++, class and structure definitions (class and struct)
are used for the encapsulation provisions in combination with access keywords private, protected and
public.
The public keyword shows that access to the members that stand behind it, is open without
restrictions. Without this keyword, class members are locked by default. Private members are
accessible only by member functions only of its class.
Protected class functions are available to class functions not only in its class, but also in its inheritor
classes. Public class functions are available for any function within the scope of the class declaration.
The protection makes possible to hide part of the class implementation, thus preventing unexpected
changes in the structure of data. Access restriction or data hiding is a feature of the object-oriented
programming.
Usually, class functions are protected and declared with the protected modifier, the reading and
writing of the values are performed by using special so-called set-and get-methods that are defined by
the publics access modifier.
Example:
class CPerson
{
protected:
string m_name; // name
public:
void SetName(string n){m_name=n;}// sets name
string GetName(){return (m_name);} // returns name
};
This approach offers several advantages. First, by function name we can understand what it does -
sets or gets the value of a class member. Secondly, perhaps in the future we will need to change the
type of the m_name CPerson variable in the CPerson class or in any it's derivative classes.
In this case, we'll need just to change the implementation of functions SetName() 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.
Hierarchy is a method that allows to copy the elements in all their diversity and complexity. It
introduces the objects classification. For example, the periodic table of elements has gases. They
possess to properties inherent 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. Such a hierarchy allows to interpret behaviour of
inert gases easily. We know that their atoms contain protons and electrons, that is true for all other
elements.
We know that they are in a gaseous state at room temperature, like all the gases. We know that no
gas from inert gas subclass enters usual chemical reaction with other elements, and its 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, square 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 CShape, 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 CShape 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. When 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 on 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 CShape should be
inherited as protected and public members of the derived class CCircle.
The private class members of the base class are not available for the derived class. The public
inheritance also means that derived classes (CCircle and CSquare) are CShapes. That is, the Square
(CSquare) is a shape (CShape), but the shape does not necessarily have to be a square.
The derived class is a modification of the base class, it inherits the protected and public members of
the base class. The constructors and destructors of the base class cannot be inherited. In addition to
members of the base class, 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.
See also
Structures 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 CShape, 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 re-define this function in accordance with rules of calculating the area of a particular shape.
For a square (class CSquare), the area is calculated through its sides, for a circle (class CCircle), area
is expressed through its radius etc. We can create an array to store objects of CShape 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.
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 the area of the square and circle, we need the corresponding values of m_radius and
m_square_side, so we have added the functions SetRadius and SetSide() in the declaration of the
corresponding class.
It is assumed that object of different types (CCircle and CSquare) derived from one base type CShape
are used in our program. Polymorphism allows creating an array of objects of the base CShape 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 CShape
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);
//shapes[2]=circle;
//--- 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
Standard Library
Overload
Within one class it is possible to define two or more methods that use the same name, but have
different numbers of parameters. When this occurs, methods are called overloaded and such a process
is referred to as method overloading.
If the called function has no exact match, the compiler searches for a suitable function on three levels
sequentially:
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. Within one level, there can't be more than
one suitable function.
See also
Reloading Functions
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. Structures
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. When 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
CTetrisShape with the virtual function Draw is defined in the included file MT5_TetisShape.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; }
Further, for each derived class, this function is implemented in accordance with characteristics of a
descendant class. For example, the first shape CTetrisShape1 has its own implementation of the Draw
() function:
The Square shape is described by class CTetrisShape6 and has its own implementation of the Draw()
method:
{
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();
//---
}
See also
Standard Library
Chart constants are used when working with price charts: opening, navigation, setting parameters;
Objects constants are intended for processing graphical objects that can be created and displayed in
charts;
Indicators constants are used for working with standard and custom indicators;
Environment state describe properties of a mql5-program, show information about a client terminal,
security and current account;
Trade constants allow to specify a variety of information in the course of trading;
Named constants are constants of the MQL5 language;
Data structures describe data storage formats used;
Codes of errors and warnings describe compiler messages and trading server answers to trade
requests;
In/out constants are designed for working with file functions and displaying messages on the screen
by the MessageBox() function.
Chart Constants
Constants describing various properties of charts are divided into the following groups:
ENUM_CHART_EVENT
ID Description
CHARTEVENT_KEYDOWN Keystrokes
For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through this parameters
are listed in the below table.
properties dialog
ID of the user CHARTEVENT_CU Value set by the Value set by the Value set by the
event under the STOM+N EventChartCusto EventChartCusto EventChartCusto
N number m() fubction m() function m() function
Example:
#define KEY_NUMPAD_5 12
#define KEY_LEFT 37
#define KEY_UP 38
#define KEY_RIGHT 39
#define KEY_DOWN 40
#define KEY_NUMLOCK_DOWN 98
#define KEY_NUMLOCK_LEFT 100
#define KEY_NUMLOCK_5 101
#define KEY_NUMLOCK_RIGHT 102
#define KEY_NUMLOCK_UP 104
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Print("The expert with name ",MQL5InfoString(MQL5_PROGRAM_NAME)," is running");
//---
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // Event identifier
const long& lparam, // Event parameter of long type
const double& dparam, // Event parameter of double type
const string& sparam // Event parameter of string type
)
{
//--- the left mouse button has been pressed on the chart
if(id==CHARTEVENT_CLICK)
{
Print("The coordinates of the mouse click on the chart are: x = ",lparam," y = ",dparam);
}
//--- the mouse has been clicked on the graphic object
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("The mouse has been clicked on the object with name '"+sparam+"'");
}
//--- the key has been pressed
if(id==CHARTEVENT_KEYDOWN)
{
switch(lparam)
{
case KEY_NUMLOCK_LEFT: Print("The KEY_NUMLOCK_LEFT has been pressed"); break;
case KEY_LEFT: Print("The KEY_LEFT has been pressed"); break;
case KEY_NUMLOCK_UP: Print("The KEY_NUMLOCK_UP has been pressed"); break;
case KEY_UP: Print("The KEY_UP has been pressed"); break;
case KEY_NUMLOCK_RIGHT: Print("The KEY_NUMLOCK_RIGHT has been pressed"); break;
case KEY_RIGHT: Print("The KEY_RIGHT has been pressed"); break;
case KEY_NUMLOCK_DOWN: Print("The KEY_NUMLOCK_DOWN has been pressed"); break;
case KEY_DOWN: Print("The KEY_DOWN has been pressed"); break;
case KEY_NUMPAD_5: Print("The KEY_NUMPAD_5 has been pressed"); break;
case KEY_NUMLOCK_5: Print("The KEY_NUMLOCK_5 has been pressed"); break;
default: Print("Some not listed key has been pressed");
}
ChartRedraw();
}
//--- the object has been deleted
if(id==CHARTEVENT_OBJECT_DELETE)
{
See also
Event Handling Functions, Working with events
Chart Timeframes
All predefined timeframes of charts have unique identifiers. The PERIOD_CURRENT identifier means
the current period of a chart, at which a mql5-program is running.
ENUM_TIMEFRAMES
ID Description
PERIOD_M1 1 minute
PERIOD_M2 2 minutes
PERIOD_M3 3 minutes
PERIOD_M4 4 minutes
PERIOD_M5 5 minutes
PERIOD_M6 6 minutes
PERIOD_M10 10 minutes
PERIOD_M12 12 minutes
PERIOD_M15 15 minutes
PERIOD_M20 20 minutes
PERIOD_M30 30 minutes
PERIOD_H1 1 hour
PERIOD_H2 2 hours
PERIOD_H3 3 hours
PERIOD_H4 4 hours
PERIOD_H6 6 hours
PERIOD_H8 8 hours
PERIOD_H12 12 hours
PERIOD_D1 1 day
PERIOD_W1 1 week
PERIOD_MN1 1 month
Example:
string chart_name="test_Object_Chart";
Print("Let's try to create a Chart object with the name ",chart_name);
//--- If such an object does not exist - create it
if(ObjectFind(0,chart_name)<0)ObjectCreate(0,chart_name,OBJ_CHART,0,0,0,0,0);
See also
Chart Properties
Identifiers of ENUM_CHART_PROPERTY enumerations are used as parameters of functions for working
with charts. The abbreviation of r/o in the "Type property" column means that this property is read-
only and can not be changed. When accessing certain properties, it's necessary to specify an additional
parameter-modifier (modifier), which serves to indicate the number of chart subwindows. 0 means
the main window.
ENUM_CHART_PROPERTY_INTEGER
ENUM_CHART_PROPERTY_DOUBLE
ENUM_CHART_PROPERTY_STRING
Example:
int chartMode=ChartGetInteger(0,CHART_MODE);
switch(chartMode)
{
case(CHART_BARS): Print("CHART_BARS"); break;
case(CHART_CANDLES): Print("CHART_CANDLES");break;
default:Print("CHART_LINE");
}
bool shifted=ChartGetInteger(0,CHART_SHIFT);
if(shifted) Print("CHART_SHIFT = true");
else Print("CHART_SHIFT = false");
bool autoscroll=ChartGetInteger(0,CHART_AUTOSCROLL);
if(autoscroll) Print("CHART_AUTOSCROLL = true");
else Print("CHART_AUTOSCROLL = false");
int chartHandle=ChartGetInteger(0,CHART_WINDOW_HANDLE);
Print("CHART_WINDOW_HANDLE = ",chartHandle);
int windows=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("CHART_WINDOWS_TOTAL = ",windows);
if(windows>1)
{
for(int i=0;i<windows;i++)
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,i);
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,i);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,i);
Print(i+": CHART_HEIGHT_IN_PIXELS = ",height," pixels");
Print(i+": CHART_PRICE_MIN = ",priceMin);
Print(i+": CHART_PRICE_MAX = ",priceMax);
}
}
Positioning Constants
Three identifiers from the ENUM_CHART_POSITION list are the possible values of the position
parameter for the ChartNavigate() function.
ENUM_CHART_POSITION
ID Description
Example:
long handle=ChartOpen("EURUSD",PERIOD_H12);
if(handle!=0)
{
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
ChartSetInteger(handle,CHART_SHIFT,true);
ChartSetInteger(handle,CHART_MODE,CHART_LINE);
ResetLastError();
bool res=ChartNavigate(handle,CHART_END,150);
if(!res) Print("Navigate failed. Error = ",GetLastError());
ChartRedraw();
}
Chart Representation
Price charts can be displayed in three ways:
as bars;
as candlesticks;
as a line.
The specific way of displaying the price chart is set by the function ChartSetInteger(chart_handle,
CHART_MODE, chart_mode), where chart_mode is one of the values of the ENUM_CHART_MODE
enumeration.
ENUM_CHART_MODE
ID Description
To specify the mode of displaying volumes in the price chart the function ChartSetInteger
(chart_handle, CHART_SHOW_VOLUMES, volume_mode) is used, where volume_mode is one of values
of the ENUM_CHART_VOLUME_MODE enumeration.
ENUM_CHART_VOLUME_MODE
ID Description
Example:
See also
ChartOpen, ChartID
Object Constants
There are 39 graphical objects that can be created and displayed in the price chart. All constants for
working with objects are divided into 9 groups:
Object Types
When a graphical object is created using the ObjectCreate() function, it's necessary to specify the
type of object being created, which can be one of the values of the ENUM_OBJECT enumeration.
Further specifications of object properties are possible using functions for working with graphical
objects.
ENUM_OBJECT
ID Description
OBJ_RECTANGLE Rectangle
OBJ_TRIANGLE Triangle
OBJ_ELLIPSE Ellipse
OBJ_ARROW_THUMB_UP Thumbs Up
OBJ_ARROW_UP Arrow Up
OBJ_ARROW Arrow
OBJ_TEXT Text
OBJ_LABEL Label
OBJ_BUTTON Button
OBJ_CHART Chart
OBJ_BITMAP Bitmap
OBJ_EDIT Edit
Object Properties
Every graphical object in a price chart has a certain set of properties. Values of object properties are
wet up and received by corresponding functions for working with graphical objects. For each object
type there is its own set of properties. Here al possible values from the ENUM_OBJECT_PROPERTY
enumeration family are listed. Some properties require clarification, such as the level number for the
Fibonacci extension object. In such cases it is necessary to specify the value of the modifier
parameter in the functions of ObjectSet...() and ObjectGet...().
ENUM_OBJECT_PROPERTY_INTEGER
"Bitmap" (OBJ_BITMAP_LABEL
and OBJ_BITMAP). The value is
set in pixels relative to the
upper left corner of the original
image.
OBJPROP_CHART_SCALE The scale for the Chart object int value in the range 0–5
When using chart operations for the "Chart" object (OBJ_CHART), the following limitations are
imposed:
For objects OBJ_BITMAP_LABEL and OBJ_BITMAP, a special mode of image display can be set
programmatically. In this mode, only part of an original image, at which a rectangular visible area is
applied, while the rest of the image becomes invisible. The size of this area should be set using the
properties OBJPROP_XSIZE and OBJPROP_YSIZE. The visible area can be "moved" only within the
original image using the properties OBJPROP_XOFFSET and OBJPROP_YOFFSET.
ENUM_OBJECT_PROPERTY_DOUBLE
ENUM_OBJECT_PROPERTY_STRING
For the OBJ_RECTANGLE_LABEL object ("Rectangle label") one of the three design modes can be set,
to which the following values of ENUM_BORDER_TYPE correspond.
ENUM_BORDER_TYPE
Identifier Description
Example:
#define UP "\x0431"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
string label_name="my_OBJ_LABEL_object";
if(ObjectFind(0,label_name)<0)
{
Print("Object ",label_name," not found. Error code = ",GetLastError());
//--- create Label object
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- set X coordinate
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- set Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
//--- define text color
ObjectSetInteger(0,label_name,OBJPROP_COLOR,clrWhite);
//--- define text for object Label
ObjectSetString(0,label_name,OBJPROP_TEXT,UP);
//--- define font
ObjectSetString(0,label_name,OBJPROP_FONT,"Wingdings");
//--- define font size
ObjectSetInteger(0,label_name,OBJPROP_FONTSIZE,10);
//--- 45 degrees rotation clockwise
ObjectSetDouble(0,label_name,OBJPROP_ANGLE,-45);
//--- disable for mouse selecting
ObjectSetInteger(0,label_name,OBJPROP_SELECTABLE,false);
//--- draw it on the chart
ChartRedraw(0);
}
}
ENUM_ANCHOR_POINT
ID Description
Example:
string text_name="my_OBJ_TEXT_object";
if(ObjectFind(0,text_name)<0)
{
Print("Object ",text_name," not found. Error code = ",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Create object Label
ObjectCreate(0,text_name,OBJ_TEXT,0,TimeCurrent(),chart_max_price);
//--- Set color of the text
ObjectSetInteger(0,text_name,OBJPROP_COLOR,clrWhite);
//--- Set background color
ObjectSetInteger(0,text_name,OBJPROP_BGCOLOR,clrGreen);
//--- Set text for the Label object
ObjectSetString(0,text_name,OBJPROP_TEXT,TimeToString(TimeCurrent()));
//--- Set text font
ObjectSetString(0,text_name,OBJPROP_FONT,"Trebuchet MS");
//--- Set font size
ObjectSetInteger(0,text_name,OBJPROP_FONTSIZE,10);
//--- Bind to the upper right corner
ObjectSetInteger(0,text_name,OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
//--- Rotate 90 degrees counter-clockwise
ObjectSetDouble(0,text_name,OBJPROP_ANGLE,90);
//--- Forbid the selection of the object by mouse
ObjectSetInteger(0,text_name,OBJPROP_SELECTABLE,false);
//--- redraw object
ChartRedraw(0);
}
Graphical objects Arrow (OBJ_ARROW) have only 2 ways of linking their coordinates. Identifiers are
listed in ENUM_ARROW_ANCHOR.
ENUM_ARROW_ANCHOR
ID Description
Example:
void OnStart()
{
//--- Auxiliary arrays
double Ups[],Downs[];
datetime Time[];
//--- Set the arrays as timeseries
ArraySetAsSeries(Ups,true);
ArraySetAsSeries(Downs,true);
ArraySetAsSeries(Time,true);
//--- Create handle of the Indicator Fractals
int FractalsHandle=iFractals(NULL,0);
Print("FractalsHandle = ",FractalsHandle);
//--- Set Last error value to Zero
ResetLastError();
//--- Try to copy the values of the indicator
int copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Print("Unable to copy the upper fractals. Error = ",GetLastError());
return;
}
ResetLastError();
//--- Try to copy the values of the indicator
copied=CopyBuffer(FractalsHandle,1,0,1000,Downs);
if(copied<=0)
{
Print("Unable to copy the bottom fractals. Error = ",GetLastError());
return;
}
ResetLastError();
//--- Copy timeseries containing the opening bars of the last 1000 ones
copied=CopyTime(NULL,0,0,1000,Time);
if(copied<=0)
{
Print("Unable to copy the Opening Time of the last 1000 bars");
return;
}
After the script execution the chart will look like in this figure.
Label (OBJ_LABEL);
Button (OBJ_BUTTON);
Chart (OBJ_CHART);
Bitmap Label (OBJ_BITMAP_LABEL);
Rectangle Label (OBJ_RECTANGLE_LABEL);
Edit (OBJ_EDIT).
In order to specify the chart corner, from which X and Y coordinates will be measured in pixels, use
ObjectSetInteger(chartID, name, OBJPROP_CORNER, chart_corner), where:
ENUM_BASE_CORNER
ID Description
Example:
Visibility of Objects
The combination of object visibility flags determines chart timeframes, where the object is visible.
To set/get the value of the OBJPROP_TIMEFRAMES property, you can use functions ObjectSetInteger()
/ObjectGetInteger().
ID Value Description
Visibility flags can be combined using the symbol "|", for example, the combination of flags
OBJ_PERIOD_M10|OBJ_PERIOD_H4 means that the object will be visible on the 10-minute and 4-hour
timeframes.
Example:
void OnStart()
{
//---
string highlevel="PreviousDayHigh";
string lowlevel="PreviousDayLow";
double prevHigh; // The previous day High
double prevLow; // The previous day Low
double highs[],lows[]; // Arrays for High and Low
{
Print("Could not get High prices over the past 2 days, Error = ",GetLastError());
}
See also
ENUM_ELLIOT_WAVE_DEGREE
ID Description
ELLIOTT_SUPERCYCLE Supercycle
ELLIOTT_CYCLE Cycle
ELLIOTT_PRIMARY Primary
ELLIOTT_INTERMEDIATE Intermediate
ELLIOTT_MINOR Minor
ELLIOTT_MINUTE Minute
ELLIOTT_MINUETTE Minuette
ELLIOTT_SUBMINUETTE Subminuette
Example:
for(int i=0;i<ObjectsTotal(0);i++)
{
string currobj=ObjectName(0,i);
if((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE3) ||
((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE5)))
{
//--- set the marking level in INTERMEDIATE
ObjectSetInteger(0,currobj,OBJPROP_DEGREE,ELLIOTT_INTERMEDIATE);
//--- show lines between tops of waves
ObjectSetInteger(0,currobj,OBJPROP_DRAWLINES,true);
//--- set line color
ObjectSetInteger(0,currobj,OBJPROP_COLOR,clrBlue);
//--- set line width
ObjectSetInteger(0,currobj,OBJPROP_WIDTH,5);
//--- set description
ObjectSetString(0,currobj,OBJPROP_TEXT,"test script");
}
}
Gann Objects
For Gann Fan (OBJ_GANNFAN) and Gann Grid (OBJ_GANNGRID) of two values of
ENUM_GANN_DIRECTION can be specified, which will set the trend direction.
ENUM_GANN_DIRECTION
ID Description
To set the scale of the main line as 1x1, use function ObjectSetDouble(chart_handle,
gann_object_name, OBJPROP_SCALE, scale), where:
void OnStart()
{
//---
string my_gann="OBJ_GANNFAN object";
if(ObjectFind(0,my_gann)<0)// Object not found
{
//--- Inform about the failure
Print("Object ",my_gann," not found. Error code = ",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Get the minimal price of the chart
double chart_min_price=ChartGetDouble(0,CHART_PRICE_MIN,0);
//--- How many bars are shown in the chart?
int bars_on_chart=ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- Create an array, to write the opening time of each bar to
datetime Time[];
//--- Arrange access to the array as that of timeseries
ArraySetAsSeries(Time,true);
//--- Now copy data of bars visible in the chart into this array
int times=CopyTime(NULL,0,0,bars_on_chart,Time);
if(times<=0)
{
Print("Could not copy the array with the open time!");
return;
}
//--- Preliminary preparations completed
Web Colors
The following color constants are defined for the color type:
clrM aroon clrIndigo clrM idnigh clrDarkBlu clrDarkOliv clrSaddleB clrForestG clrOliveDra
tBlue e eGreen rown reen b
clrLightSe clrDarkViol clrFireBric clrM edium clrM edium clrChocola clrCrimson clrSteelBlu
aGreen et k VioletRed SeaGreen te e
clrIndianR clrM edium clrGreenY clrM edium clrDarkSea clrTomato clrRosyBro clrOrchid
ed Orchid ellow Aquamarin Green wn
e
clrM edium clrPaleViol clrCoral clrCornflo clrDarkGra clrSandyBr clrM edium clrTan
Purple etRed werBlue y own SlateBlue
Color can be set to an object using the ObjectSetInteger() function. For setting color to custom
indicators the PlotIndexSetInteger() function is used. For getting color values there are similar
functions ObjectGetInteger() and PlotIndexGetInteger().
Example:
Wingdings
Characters of Wingdings used with the OBJ_ARROW object:
Example:
void OnStart()
{
//---
string up_arrow="up_arrow";
datetime time=TimeCurrent();
double lastClose[1];
int close=CopyClose(Symbol(),Period(),0,1,lastClose); // Get the Close price
//--- If the price was obtained
if(close>0)
{
ObjectCreate(0,up_arrow,OBJ_ARROW,0,0,0,0,0); // Create an arrow
ObjectSetInteger(0,up_arrow,OBJPROP_ARROWCODE,241); // Set the arrow code
ObjectSetInteger(0,up_arrow,OBJPROP_TIME,time); // Set time
ObjectSetDouble(0,up_arrow,OBJPROP_PRICE,lastClose[0]);// Set price
ChartRedraw(0); // Draw arrow now
}
else
Print("Unable to get the latest Close price!");
}
Indicators Constants
There are 37 predefined technical indicators, which can be used in programs written in the MQL5
language. In addition, there is an opportunity to create custom indicators using the iCustom()
function. All constants required for that are divided into 5 groups:
Price constants – for selecting the type of price or volume, on which an indicator is calculated;
Smoothing methods – built-in smoothing methods used in indicators;
Indicator lines – identifiers of indicator buffers when accessing indicator values using CopyBuffer();
Drawing styles – for indicating one of 18 types of drawing and setting the line drawing style;
Custom indicators properties are used in functions for working with custom indicators;
Types of indicators are used for specifying the type of technical indicator when creating a handle
using IndicatorCreate();
Identifiers of data types are used for specifying the type of data passed in an array of the MqlParam
type into the IndicatorCreate() function.
Price Constants
Calculations of technical indicators require price values and/or values of volumes, on which
calculations will be performed. There are 7 predefined identifiers from the ENUM_APPLIED_PRICE
enumeration, used to specify the desired price base for calculations.
ENUM_APPLIED_PRICE
ID Description
If the volume is used in calculations, it's necessary to specify one of the two values from the
ENUM_APPLIED_VOLUME enumeration.
ENUM_APPLIED_VOLUME
ID Description
ENUM_STO_PRICE
ID Description
If a technical indicator uses for calculations price data, type of which is set by ENUM_APPLIED_PRICE,
then handle of any indicator (built in the terminal or written by a user) can be used as the input price
series. In this case, values of the zero buffer of the indicator indicator will be used for calculations.
This makes it easy to build values of one indicator using values of another indicator. The handle of a
custom indicator is created by calling the iCustom() function.
Example:
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 2
//--- input parameters
input int RSIperiod=14; // Period for calculating the RSI
input int Smooth=8; // Smoothing period RSI
input ENUM_MA_METHOD meth=MODE_SMMA; // Method of smoothing
//---- plot RSI
#property indicator_label1 "RSI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//---- plot RSI_Smoothed
#property indicator_label2 "RSI_Smoothed"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrNavy
#property indicator_style2 STYLE_SOLID
#property indicator_width2 1
//--- indicator buffers
double RSIBuffer[]; // Here we store the values of RSI
double RSI_SmoothedBuffer[]; // Here will be smoothed values of RSI
int RSIhandle; // Handle to the RSI indicator
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,RSIBuffer,INDICATOR_DATA);
SetIndexBuffer(1,RSI_SmoothedBuffer,INDICATOR_DATA);
IndicatorSetString(INDICATOR_SHORTNAME,"iRSI");
IndicatorSetInteger(INDICATOR_DIGITS,2);
//---
RSIhandle=iRSI(NULL,0,RSIperiod,PRICE_CLOSE);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[]
)
Smoothing Methods
Many technical indicators are based on various methods of the price series smoothing. Some standard
technical indicators require specification of the smoothing type as an input parameter. For specifying
the desired type of smoothing, identifiers listed in the ENUM_MA_METHOD enumeration are used.
ENUM_MA_METHOD
ID Description
Example:
double ExtJaws[];
double ExtTeeth[];
double ExtLips[];
//---- handles for moving averages
int ExtJawsHandle;
int ExtTeethHandle;
int ExtLipsHandle;
//--- get MA's handles
ExtJawsHandle=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtTeethHandle=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtLipsHandle=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN);
Indicators Lines
Some technical indicators have several buffers drawn in the chart. Numbering of indicator buffers
starts with 0. When copying indicator values using the CopyBuffer() function into an array of the
double type, for some indicators one may indicate the identifier of a copied buffer instead of its
number.
Identifiers of indicator lines permissible when copying values of iMACD(), iRVI() and iStochastic().
Identifiers of indicator lines permissible when copying values of ADX() and ADXW().
Identifiers of indicator lines permissible when copying values of iEnvelopes() and iFractals().
Drawing Styles
When creating a custom indicator, you can specify one of 18 types of graphical plotting (as displayed
in the main chart window or a chart subwindow), whose values are specified in the ENUM_DRAW_TYPE
enumeration.
In one custom indicator, it is permissible to use any indicator building/drawing types. Each
construction type requires specification of one to five global arrays for storing data necessary for
drawing. These data arrays must be bound with indicator buffers using the SetIndexBuffer() function.
The type of data from ENUM_INDEXBUFFER_TYPE should be specified for each buffer.
Depending on the drawing style, you may need one to four value buffers (marked as
INDICATOR_DATA). If a style admits dynamic alternation of colors (all styles contain COLOR in their
names), then you'll need one more buffer of color (indicated type INDICATOR_COLOR_INDEX). The
color buffer are always bound after value buffers corresponding to the style.
ENUM_DRAW_TYPE
DRAW_LINE Line 1 0
DRAW_SECTION Section 1 0
buffers
DRAW_COLOR_CANDL Multicolored 4 1
ES candlesticks
To refine the display of the selected drawing type identifiers listed in ENUM_PLOT_PROPERTY are
used.
ENUM_PLOT_PROPERTY_INTEGER
ENUM_PLOT_PROPERTY_DOUBLE
ENUM_PLOT_PROPERTY_STRING
5 styles can be used for drawing lines in custom indicators. They are valid only for the line thickness 0
or 1.
ENUM_LINE_STYLE
ID Description
To set the line drawing style and the type of drawing, the PlotIndexSetInteger() function is used. For
the Fibonacci extensions the thickness and drawing style of levels can be indicated using the
ObjectSetInteger() function.
Example:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- indicator buffers
double MABuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Bind the Array to the indicator buffer with index 0
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
//--- Set the line drawing
PlotIndexSetInteger(0,PLOT_DRAW_TYPE,DRAW_LINE);
//--- Set the style line
PlotIndexSetInteger(0,PLOT_LINE_STYLE,STYLE_DOT);
//--- Set line color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrRed);
ENUM_INDEXBUFFER_TYPE
ID Description
INDICATOR_COLOR_INDEX Color
A custom indicator has a lot of settings to provide convenient displaying. These settings are made
through the assignment of corresponding indicator properties using functions IndicatorSetDouble(),
IndicatorSetInteger() and IndicatorSetString(). Identifiers of indicator properties are listed in the
ENUM_CUSTOMIND_PROPERTY enumeration.
ENUM_CUSTOMIND_PROPERTY_INTEGER
ENUM_CUSTOMIND_PROPERTY_DOUBLE
ENUM_CUSTOMIND_PROPERTY_STRING
Examples:
When creating an indicator of type IND_CUSTOM, the type field of the first element of an array of
input parameters MqlParam must have the TYPE_STRING value of the enumeration ENUM_DATATYPE,
while the field string_value of the first element must contain the name of the custom indicator.
ENUM_INDICATOR
Identifier Indicator
IND_AD Accumulation/Distribution
IND_ALLIGATOR Alligator
IND_DEMARKER DeMarker
IND_ENVELOPES Envelopes
IND_FRACTALS Fractals
IND_MACD MACD
IND_MOMENTUM Momentum
IND_OSMA OsMA
IND_VOLUMES Volumes
ENUM_DATATYPE
TYPE_BOOL bool
TYPE_CHAR char
TYPE_UCHAR uchar
TYPE_SHORT short
TYPE_USHORT ushort
TYPE_COLOR color
TYPE_INT int
TYPE_UINT uint
TYPE_DATETIME datetime
TYPE_LONG long
TYPE_ULONG ulong
TYPE_FLOAT float
TYPE_DOUBLE double
TYPE_STRING string
Each element of the array describes the corresponding input parameter of a created technical
indicator, so the type and order of elements in the array must be strictly maintained in accordance
with the description.
Environment State
Constants describing the current runtime environment of an mql5-program are divided into groups:
ENUM_TERMINAL_INFO_INTEGER
File operations can be performed only in two directories; corresponding paths can be obtained using
the request for TERMINAL_DATA_PATH and TERMINAL_COMMONDATA_PATH properties.
ENUM_TERMINAL_INFO_STRING
//+------------------------------------------------------------------+
//| Check_TerminalPaths.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
Print("TERMINAL_PATH = ",TerminalInfoString(TERMINAL_PATH));
Print("TERMINAL_DATA_PATH = ",TerminalInfoString(TERMINAL_DATA_PATH));
Print("TERMINAL_COMMONDATA_PATH = ",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
}
As result of the script execution in the Experts Journal you will see a messages, like the following:
ENUM_MQL5_INFO_INTEGER
ENUM_MQL5_INFO_STRING
Information about the type of the running program, values of ENUM_PROGRAM_TYPE are used.
ENUM_PROGRAM_TYPE
Identifier Description
PROGRAM_SCRIPT Script
PROGRAM_EXPERT Expert
PROGRAM_INDICATOR Indicator
Example:
ENUM_PROGRAM_TYPE mql_program=(ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE);
switch(mql_program)
{
case PROGRAM_SCRIPT:
{
Print(__FILE__+" is script");
break;
}
case PROGRAM_EXPERT:
{
Print(__FILE__+" is Expert Advisor");
break;
}
case PROGRAM_INDICATOR:
{
Print(__FILE__+" is custom indicator");
break;
}
default:Print("MQL5 type value is ",mql_program);
}
Symbol properties
To obtain the current market information there are several functions: SymbolInfoInteger(),
SymbolInfoDouble() and SymbolInfoString(). The first parameter is the symbol name, the values of the
second function parameter can be one of the identifiers of ENUM_SYMBOL_INFO_INTEGER,
ENUM_SYMBOL_INFO_DOUBLE and ENUM_SYMBOL_INFO_STRING.
ENUM_SYMBOL_INFO_INTEGER
ION
ENUM_SYMBOL_INFO_DOUBLE
ENUM_SYMBOL_INFO_STRING
For each symbol several expiration modes of pending orders can be specified. A flag is matched to
each mode. Flags can be combined using the operation of logical OR (|), for example,
SYMBOL_EXPIRATION_GTC|SYMBOL_EXPIRATION_SRECIFIED. In order to check whether a certain
mode is allowed for the symbol, the result of the logical AND (&) should be compared to the mode flag.
If flag SYMBOL_EXPIRATION_SRECIFIED is specified for a symbol, then while sending a pending order,
you may specify the moment this pending order is valid till.
Example:
//+------------------------------------------------------------------+
//| Checks if the specified expiration mode is allowed |
//+------------------------------------------------------------------+
bool IsExpirationTypeAllowed(string symbol,int exp_type)
{
//--- Obtain the value of the property that describes allowed expiration modes
int expiration=(int)SymbolInfoInteger(symbol,SYMBOL_EXPIRATION_MODE);
//--- Return true, if mode exp_type is allowed
return((expiration&exp_type)==exp_type);
}
When sending an order, you can specify the filling policy for the volume set in the order. Allowed order
filling modes for each symbol are specified in the table. You can set several modes for one symbol by
combining flags. The flags can be combined by the operation of the logical OR (|), for example,
SYMBOL_FILLING_ALL_OR_NONE|SYMBOL_CANCEL_REMAIND. In order to check whether a certain
mode is allowed for the symbol, the result of the logical AND (&) should be compared to the mode flag.
Example:
//+------------------------------------------------------------------+
//| Checks if the specified expiration mode is allowed |
//+------------------------------------------------------------------+
bool IsFiilingTypeAllowed(string symbol,int fill_type)
{
//--- Obtain the value of the property that describes allowed expiration modes
int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed
return((filling & fill_type)==fill_type);
}
The ENUM_SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin
requirements for a symbol are calculated.
ENUM_SYMBOL_CALC_MODE
There are several symbol trading modes. Information about trading modes of a certain symbol is
reflected in the values of enumeration ENUM_SYMBOL_TRADE_MODE.
ENUM_SYMBOL_TRADE_MODE
Identifier Description
Possible deal execution modes for a certain symbol are defined in enumeration
ENUM_SYMBOL_TRADE_EXECUTION.
ENUM_SYMBOL_TRADE_EXECUTION
Identifier Description
ENUM_SYMBOL_SWAP_MODE
Identifier Description
in a year)
ENUM_DAY_OF_WEEK
Identifier Description
SUNDAY Sunday
MONDAY Monday
TUESDAY Tuesday
WEDNESDAY Wednesday
THURSDAY Thursday
FRIDAY Friday
SATURDAY Saturday
Account Properties
To obtain information about the current account there are several functions: AccountInfoInteger(),
AccountInfoDouble() and AccountInfoString(). The function parameter values can accept values from
the corresponding ENUM_ACCOUNT_INFO enumerations.
ENUM_ACCOUNT_INFO_INTEGER
ENUM_ACCOUNT_INFO_DOUBLE
the set
ACCOUNT_MARGIN_SO_MODE
is expressed in percents or in
the deposit currency
ENUM_ACCOUNT_INFO_STRING
ENUM_ACCOUNT_TRADE_MODE
Identifier Description
ENUM_ACCOUNT_STOPOUT_MODE
Identifier Description
Testing Statistics
After the testing is over, different parameters of the trading results statistics are calculated. The
values of the parameters can be obtained using the TesterStatistics() function, by specifying the
parameter ID from the ENUM_STATISTICS enumeration.
Although two types of parameters (int and double) are used for calculating statistics, the function
returns all values in the double form. All the statistic values of the double type are expressed in the
deposit currency by default, unless otherwise specified.
ENUM_STATISTICS
Trade Constants
Various constants used for programming trading strategies, are divided into the following groups:
ENUM_SERIES_INFO_INTEGER
Order Properties
Requests to execute trade operations are formalized as orders. Each order has a variety of properties
for reading. Information on them can be obtained using functions OrderGet...() and
HistoryOrderGet...().
ENUM_ORDER_PROPERTY_INTEGER
ENUM_ORDER_PROPERTY_DOUBLE
ENUM_ORDER_PROPERTY_STRING
When sending a trade request using the OrderSend() function, some operations require the indication
of the order type. The order type is specified in the type field of the special structure
MqlTradeRequest, and can accept values of the ENUM_ORDER_TYPE enumeration.
ENUM_ORDER_TYPE
Identifier Description
Each order has a status that describes its state. To obtain information, use OrderGetInteger() or
HistoryOrderGetInteger() with the ORDER_STATE modifier. Allowed values are stored in the
ENUM_ORDER_STATE enumeration.
ENUM_ORDER_STATE
Identifier Description
When sending a trade request using the OrderSend() function, the filling policy can be set for an order
in the type_filling field of the special structure MqlTradeRequest. Values of the
ENUM_ORDER_TYPE_FILLING enumeration are allowed. To obtain the value of this property, use the
function OrderGetInteger() or HistoryOrderGetInteger() with the ORDER_TYPE_FILLING modifier.
ENUM_ORDER_TYPE_FILLING
Identifier Description
The order validity period can be set in the type_time field of the special structure MqlTradeRequest
when sending a trade request using the OrderSend() function. Values of the ENUM_ORDER_TYPE_TIME
enumeration are allowed. To obtain the value of this property use the function OrderGetInteger() or
HistoryOrderGetInteger() with the ORDER_TYPE_TIME modifier.
ENUM_ORDER_TYPE_TIME
Identifier Description
Position Properties
Execution of trade operations results in the opening of a position, changing of its volume and/or
direction, or its disappearance. Trade operations are conducted based on orders, sent by the
OrderSend() function in the form of trade requests. For each financial security (symbol) only one open
position is possible. A position has a set of properties available for reading by the PositionGet...()
functions.
ENUM_POSITION_PROPERTY_INTEGER
ENUM_POSITION_PROPERTY_DOUBLE
ENUM_POSITION_PROPERTY_STRING
Direction of an open position (buy or sell) is defined by the value from the ENUM_POSITION_TYPE
enumeration. In order to obtain the type of an open position use the PositionGetInteger() function
with the POSITION_TYPE modifier.
ENUM_POSITION_TYPE
Identifier Description
POSITION_TYPE_BUY Buy
POSITION_TYPE_SELL Sell
Deal Properties
A deal is the reflection of the fact of a trade operation execution based on an order that contains a
trade request. Each trade is described by properties that allow to obtain information about it. In order
to read values of properties, functions of the HistoryDealGet...() type are used, that return values
from corresponding enumerations.
ENUM_DEAL_PROPERTY_INTEGER
ENUM_DEAL_PROPERTY_DOUBLE
ENUM_DEAL_PROPERTY_STRING
Each deal is characterized by a type, allowed values are enumerated in ENUM_DEAL_TYPE. In order to
obtain information about the deal type, use the HistoryDealGetInteger() function with the DEAL_TYPE
modifier.
ENUM_DEAL_TYPE
Identifier Description
DEAL_TYPE_BUY Buy
DEAL_TYPE_SELL Sell
DEAL_TYPE_BALANCE Balance
DEAL_TYPE_CREDIT Credit
DEAL_TYPE_CORRECTION Correction
Deals differ not only in their types set in ENUM_DEAL_TYPE, but also in the way they change positions.
This can be a simple position opening, or accumulation of a previously opened position (market
entering), position closing by an opposite deal of a corresponding volume (market exiting), or position
reversing, if the opposite-direction deal covers the volume of the previously opened position.
All these situations are described by values from the ENUM_DEAL_ENTRY enumeration. In order to
receive this information about a deal, use the HistoryDealGetInteger() function with the DEAL_ENTRY
modifier.
ENUM_DEAL_ENTRY
Identifier Description
DEAL_ENTRY_IN Entry in
DEAL_ENTRY_INOUT Reverse
ENUM_TRADE_REQUEST_ACTIONS
Identifier Description
To obtain information about the current state of the DOM by MQL5 means, the MarketBookGet()
function is used, which places the DOM "screen shot" into the MqlBookInfo array of structures. Each
element of the array in the type field contains information about the direction of the order - the value
of the ENUM_BOOK_TYPE enumeration.
ENUM_BOOK_TYPE
Identifier Description
See also
Structures and classes, Structure of the DOM, Trade operation types, Market Info
Named Constants
All constants used in MQL5 can be divided into the following groups:
Predefined Macrosubstitutions
To simplify the debugging process and obtain information about operation of a mql5-program, there
are special macro constant, values of which are set at the moment of compilation. The easiest way to
use these constants is outputting values by the Print() function, as it's shown in the example.
Constant Description
Example:
Mathematical Constants
Special constants containing values are reserved for some mathematical expressions. These constants
can be used in any place of the program instead of calculating their values using mathematical
functions.
M_E e 2.71828182845904523536
M_PI pi 3.14159265358979323846
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the values of constants
Print("M_E = ",DoubleToString(M_E,16));
Print("M_LOG2E = ",DoubleToString(M_LOG2E,16));
Print("M_LOG10E = ",DoubleToString(M_LOG10E,16));
Print("M_LN2 = ",DoubleToString(M_LN2,16));
Print("M_LN10 = ",DoubleToString(M_LN10,16));
Print("M_PI = ",DoubleToString(M_PI,16));
Print("M_PI_2 = ",DoubleToString(M_PI_2,16));
Print("M_PI_4 = ",DoubleToString(M_PI_4,16));
Print("M_1_PI = ",DoubleToString(M_1_PI,16));
Print("M_2_PI = ",DoubleToString(M_2_PI,16));
Print("M_2_SQRTPI = ",DoubleToString(M_2_SQRTPI,16));
Print("M_SQRT2 = ",DoubleToString(M_SQRT2,16));
Print("M_SQRT1_2 = ",DoubleToString(M_SQRT1_2,16));
Example:
void OnStart()
{
//--- print the constant values
printf("CHAR_MIN = %d",CHAR_MIN);
printf("CHAR_MAX = %d",CHAR_MAX);
printf("UCHAR_MAX = %d",UCHAR_MAX);
printf("SHORT_MIN = %d",SHORT_MIN);
printf("SHORT_MAX = %d",SHORT_MAX);
printf("USHORT_MAX = %d",USHORT_MAX);
printf("INT_MIN = %d",INT_MIN);
printf("INT_MAX = %d",INT_MAX);
printf("UINT_MAX = %u",UINT_MAX);
printf("LONG_MIN = %I64d",LONG_MIN);
printf("LONG_MAX = %I64d",LONG_MAX);
printf("ULONG_MAX = %I64u",ULONG_MAX);
printf("EMPTY_VALUE = %.16e",EMPTY_VALUE);
printf("DBL_MIN = %.16e",DBL_MIN);
printf("DBL_MAX = %.16e",DBL_MAX);
printf("DBL_EPSILON = %.16e",DBL_EPSILON);
printf("DBL_DIG = %d",DBL_DIG);
printf("DBL_MANT_DIG = %d",DBL_MANT_DIG);
printf("DBL_MAX_10_EXP = %d",DBL_MAX_10_EXP);
printf("DBL_MAX_EXP = %d",DBL_MAX_EXP);
printf("DBL_MIN_10_EXP = %d",DBL_MIN_10_EXP);
printf("DBL_MIN_EXP = %d",DBL_MIN_EXP);
printf("FLT_MIN = %.8e",FLT_MIN);
printf("FLT_MAX = %.8e",FLT_MAX);
printf("FLT_EPSILON = %.8e",FLT_EPSILON);
}
The uninitialization reason code is also passed as a parameter of the predetermined function OnDeinit
(const int reason).
Example:
case REASON_CHARTCLOSE:
text="Chart was closed";break;
case REASON_PARAMETERS:
text="Input-parameter was changed";break;
case REASON_RECOMPILE:
text="Program "+__FILE__+" was recompiled";break;
case REASON_REMOVE:
text="Program "+__FILE__+" was removed from chart";break;
case REASON_TEMPLATE:
text="New template was applied to chart";break;
default:text="Another reason";
}
//---
return text;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- The first way to get the uninitalization reason code
Print(__FUNCTION__,"_Uninitalization reason code = ",reason);
//--- The second way to get the uninitalization reason code
Print(__FUNCTION__,"_UninitReason = ",getUnitReasonText(_UninitReason));
}
Objects created by the new() operator are of POINTER_DYNAMIC type. The delete() operator can and
should be used only for such pointers.
All other pointers are of POINTER_AUTOMATIC type, which means that this object has been created
automatically by the mql5 program environment. Such objects are deleted automatically after being
used.
ENUM_POINTER_TYPE
Constant Description
See also
Runtime errors, Object Delete Operator delete, CheckPointer
Other Constants
The CLR_NONE constant is used to outline the absence of color, it means that the graphical object or
graphical series of an indicator will not be plotted. This constant was not included into the Web-color
constants list, but it can be applied everywhere where the color arguments are required.
The INVALID_HANDLE constant can be used for checking file handles (see FileOpen() and FileFindFirst
()).
The EMPTY_VALUE constant usually corresponds to the values of indicators that are not shown inn the
chart. For example, for built-in indicator Standard Deviation with a period of 20, the line for the first
19 bars in the history is not shown in the chart. If you create a handle of this indicator with the
iStdDev() function and copy it to an array of indicator values for these bars through CopyBuffer(), then
these values will be equal to EMPTY_VALUE.
You can choose to specify for a custom indicator your own empty value of the indicator, when the
indicator shouldn't be drawn in the chart. Use the PlotIndexSetDouble() function with the
PLOT_EMPTY_VALUE modifier.
The NULL constant can be assigned to a variable of any simple type or to an object structure or class
pointer. The NULL assignment for a string variable means the full deinitialization of this variable.
The WRONG_VALUE constant is intended for cases, when it is necessary to return value of an
enumeration, and this must be a wrong value. For example, when we need to inform that a return
value is a value from this enumeration. Let's consider as an example some function CheckLineStyle(),
which returns the line style for an object, specified by its name. If at style check by ObjectGetInteger
() the result is true, a value from ENUM_LINE_STYLE is returned; otherwise WRONG_VALUE is
returned.
void OnStart()
{
if(CheckLineStyle("MyChartObject")==WRONG_VALUE)
printf("Error line style getting.");
}
//+------------------------------------------------------------------+
//| returns the line style for an object specified by its name |
//+------------------------------------------------------------------+
ENUM_LINE_STYLE CheckLineStyle(string name)
{
long style;
//---
if(ObjectGetInteger(0,name,OBJPROP_STYLE,0,style))
return((ENUM_LINE_STYLE)style);
else
return(WRONG_VALUE);
}
The WHOLE_ARRAY constant is intended intended for functions that require specifying the number of
elements in processed arrays:
ArrayCopy();
ArrayMinimum();
ArrayMaximum();
FileReadArray();
FileWriteArray().
If you want to specify, that all the array values from a specified position till the end must be
processed, you should specify just the WHOLE_ARRAY value.
The IS_DEBUG_MODE constant can be useful when you need to slightly change the operation of a mql5
program in the debugging mode. For example, in debug mode you may need to display additional
debugging information in the terminal log or create additional graphical objects in a chart.
The following example creates a Label object and sets its description and color depending on the
script running mode. In order to run a script in the debug mode from MetaEditor, press F5. If you run
the script from the browser window in the terminal, then the color and text of the object Label will be
different.
Example:
//+------------------------------------------------------------------+
//| Check_DEBUG_MODE.mq5 |
//| Copyright © 2009, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
//+------------------------------------------------------------------+
See also
DebugBreak, Executed MQL program properties
Data Structures
MQL5 Language offers 8 predefined structures:
MqlDateTime
The date type structure contains eight fields of the int type:
struct MqlDateTime
{
int year; // Year
int mon; // Month
int day; // Day
int hour; // Hour
int min; // Minutes
int sec; // Seconds
int day_of_week; // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
int day_of_year; // Day number of the year (January 1st is assigned the number value of zero)
};
Note
The day number of the year day_of_year for the leap year, since March, will differ from a number of
the corresponding day for a non-leap year.
Example:
void OnStart()
{
//---
datetime date1=D'2008.03.01';
datetime date2=D'2009.03.01';
MqlDateTime str1,str2;
TimeToStruct(date1,str1);
TimeToStruct(date2,str2);
printf("%02d.%02d.%4d, day of year = %d",str1.day,str1.mon,
str1.year,str1.day_of_year);
printf("%02d.%02d.%4d, day of year = %d",str2.day,str2.mon,
str2.year,str2.day_of_year);
}
/* Result:
01.03.2008, day of year = 60
01.03.2009, day of year = 59
*/
See also
All input parameters of an indicator are transmitted in the form of an array of the MqlParam type, the
type field of each element of this array specifies the type of data transmitted by the element. The
indicator values must be first placed in the appropriate fields for each element (in integer_value, in
double_value or string_value) depending on what value of ENUM_DATATYPE enumeration is specified
in the type field.
If the IND_CUSTOM value is passed third as the indicator type to the IndicatorCreate() function, the
first element of the array of input parameters must have the type field with the value of TYPE_STRING
from the ENUM_DATATYPE enumeration, and the string_value field must contain the name of the
custom indicator.
MqlRates
This structure stores information about the prices, volumes and spread.
struct MqlRates
{
datetime time; // Period start time
double open; // Open price
double high; // The highest price of the period
double low; // The lowest price of the period
double close; // Close price
long tick_volume; // Tick volume
int spread; // Spread
long real_volume; // Trade volume
};
Example:
void OnStart()
{
MqlRates rates[];
int copied=CopyRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Error copying price data ",GetLastError());
else Print("Copied ",ArraySize(rates)," bars");
}
See also
MqlBookInfo
It provides information about the market depth data.
struct MqlBookInfo
{
ENUM_BOOK_TYPE type; // Order type from ENUM_BOOK_TYPE enumeration
double price; // Price
long volume; // Volume
};
Note
The DOM is available only for some symbols. To use the MqlBookInfo structure, it is sufficient to
declare a variable of such a type, so it is not necessary to specify and describe it specially.
Example:
MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo about ",Symbol());
}
else
{
Print("Failed to receive DOM for the symbol ",Symbol());
}
See also
struct MqlTradeRequest
{
ENUM_TRADE_REQUEST_ACTIONS action; // Trade operation type
ulong magic; // Expert Advisor ID (magic number)
ulong order; // Order ticket
string symbol; // Trade symbol
double volume; // Requested volume for a deal in lots
double price; // Price
double stoplimit; // StopLimit level of the order
double sl; // Stop Loss level of the order
double tp; // Take Profit level of the order
ulong deviation; // Maximal possible deviation from the requested p
ENUM_ORDER_TYPE type; // Order type
ENUM_ORDER_TYPE_FILLING type_filling; // Order execution type
ENUM_ORDER_TYPE_TIME type_time; // Order execution time
datetime expiration; // Order expiration time (for the orders of ORDER_
string comment; // Order comment
};
Fields description
Field Description
For sending orders to perform trade operations it is necessary to use the OrderSend() function. For
each trade operation it is necessary to specify obligatory fields; optional fields also may be filled.
There are seven possible cases to send a trade order:
Request Execution
This is a trade order to open a position in the Request Execution mode (trade upon current prices
request). It requires to specify the following 9 fields:
action
symbol
volume
price
sl
tp
deviation
type
type_filling
Instant Execution
This is a trade order to open a position in the Instant Execution mode (trade by flow prices). It
Market Execution
This is a trade order to open a position in the Market Execution mode. It requires to specify the
following 5 fields:
action
symbol
volume
type
type_filling
SL & TP Modification
Trade order to modify the StopLoss and/or TakeProfit price levels. It requires to specify the
following 5 fields:
action
symbol
sl
tp
deviation
Pending Order
Trade order to place a pending order. It requires to specify the following 11 fields:
action
symbol
volume
price
stoplimit
sl
tp
type
type_filling
type_time
expiration
Trade order to modify the prices of a pending order. It requires to specify the following 7 fields:
action
order
price
sl
tp
type_time
expiration
Trade order to delete a pending order. It requires to specify the following 2 fields:
action
order
See also
Description of Fields
Field Description
See also
struct MqlTradeResult
{
uint retcode; // Operation return code
ulong deal; // Deal ticket, if it is performed
ulong order; // Order ticket, if it is placed
double volume; // Deal volume, confirmed by broker
double price; // Deal price, confirmed by broker
double bid; // Current Bid price
double ask; // Current Ask price
string comment; // Broker comment to operation (by default it is filled by the operatio
};
Fields description
Field Description
The trade operation result is returned to a variable of the MqlTradeResult type, which is passed as the
second parameter to OrderSend() to perform a trade operations.
Example:
//+------------------------------------------------------------------+
//| Sending a trade request with the result processing |
//+------------------------------------------------------------------+
bool MyOrderSend(MqlTradeRequest request,MqlTradeResult result)
{
//--- reset the last error code to zero
ResetLastError();
//--- send request
bool success=OrderSend(request,result);
//--- if the result fails - try to find out why
if(!success)
{
int answer=result.retcode;
Print("TradeLog: Trade request failed. Error = ",GetLastError());
switch(answer)
{
//--- requote
case 10004:
{
Print("TRADE_RETCODE_REQUOTE");
Print("request.price = ",request.price," result.ask = ",
result.ask," result.bid = ",result.bid);
break;
}
//--- order is not accepted by the server
case 10006:
{
Print("TRADE_RETCODE_REJECT");
Print("request.price = ",request.price," result.ask = ",
result.ask," result.bid = ",result.bid);
break;
}
//--- invalid price
case 10015:
{
Print("TRADE_RETCODE_INVALID_PRICE");
Print("request.price = ",request.price," result.ask = ",
result.ask," result.bid = ",result.bid);
break;
}
//--- invalid SL and/or TP
case 10016:
{
Print("TRADE_RETCODE_INVALID_STOPS");
Print("request.sl = ",request.sl," request.tp = ",request.tp);
Print("result.ask = ",result.ask," result.bid = ",result.bid);
break;
}
//--- invalid volume
case 10014:
{
Print("TRADE_RETCODE_INVALID_VOLUME");
Print("request.volume = ",request.volume," result.volume = ",
result.volume);
break;
}
//--- not enough money for a trade operation
case 10019:
{
Print("TRADE_RETCODE_NO_MONEY");
Print("request.volume = ",request.volume," result.volume = ",
The variable of the MqlTick type allows obtaining values of Ask, Bid, Last and Volume within a single
call of the SymbolInfoTick() function.
Example:
void OnTick()
{
MqlTick last_tick;
//---
if(SymbolInfoTick(Symbol(),last_tick))
{
Print(last_tick.time,": Bid = ",last_tick.bid,
" Ask = ",last_tick.ask," Volume = ",last_tick.volume);
}
else Print("SymbolInfoTick() failed, error = ",GetLastError());
//---
}
See also
Return codes of the trade server – analyzing results of the trade request sent by function OrderSend
();
Compiler warnings – codes of warning messages that appear at compilation (not errors);
Compilation errors – codes of error messages at an unsuccessful attempt to compile;
Runtime errors – error codes in the performance of mql5-programs, which can be obtained using the
GetLastErtror() function.
Compiler Warnings
Compiler warnings are shown for informational purposes only and are not error messages.
Code Description
30 Overriding macro
Compilation Errors
MetaEdtior 5 shows error messages about the program errors detected by the built-in compiler during
compilation. The list of these errors is given below in table. To compile a source code into an
executable one, press F7. Programs that contain errors cannot be compiled until the errors identified
by the compiler are eliminated.
Code Description
145 No pair for "(or" [ ", i.e. ") "or"] " is absent
Runtime Errors
GetLastError() is the function that returns the last error code that is stored in the predefined variable
_LastError. This value can be reset to zero by the ResetLastError() function.
Charts
Graphical Objects
MarketInfo
History Access
Global_Variables
Account
Indicators
Depth of Market
File Operations
String Casting
User-Defined Errors
FileIsExist() functions.
One or several flags can be specified when opening a file. This is a combination of flags. The
combination of flags is written using the sign of logical OR (|), which is positioned between
enumerated flags. For example, to open a file in CSV format for reading and writing at the same time,
specify the combination FILE_READ|FILE_WRITE|FILE_CSV.
Example:
int filehandle=FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV);
There are some specific features of work when you specify read and write flags:
If FILE_READ is specified, an attempt is made to open an existing file. If a file does not exist, file
opening fails, a new file is not created.
FILE_READ|FILE_WRITE – a new file is created if the file with the specified name does not exist.
FILE_WRITE – the file is created again with a zero size.
When opening a file specification of FILE_WRITE and/or FILE_READ is required.
Flags that define the type of reading of an open file, possess priority. The highest flag is FILE_CSV,
then goes FILE_BIN, and FILE_TXT is of lowest priority. Thus, if several flags are specified at the
same time, (FILE_TXT|FILE_CSV or FILE_TXT|FILE_BIN or FILE_BIN|FILE_CSV), the flag with the
highest priority will be used.
Flags that define the type of encoding also have priority. FILE_UNICODE is of a higher priority than
FILE_ANSI. So if you specify combination FILE_UNICODE|FILE_ANSI, flag FILE_UNICODE will be used.
If a file is opened for reading as a text file (FILE_TXT or FILE_CSV), and at the file beginning a special
two-byte indication 0xff,0xfe is found, the encoding flag will be FILE_UNICODE, even if FILE_ANSI is
specified.
See also
File Functions
ENUM_FILE_POSITION
Identifier Description
See also
FileIsEnding, FileIsLineEnding
The table lists the built-in constants for some of the most popular code pages. Not mentioned code
pages can be specified by a code corresponding to the page.
See also
Client Terminal Properties
The main flags of the MessageBox() function define contents and behavior of the dialog window. This
value can be a combination of the following flag groups:
MQL5 Programs
For the mql5-program to operate, it must be compiled (Compile button or F7 key). Compilation should
pass without errors (some warnings are possible; they should be analyzed). AT this process, an
executable file with the same name and with EX5 extension must be created in the corresponding
directory, terminal_dir\MQL5\Experts, terminal_dir\MQL5\indicators or terminal_dir\MQL5\scripts.
This file can be run.
Expert Advisors, custom indicators and scripts are attached to one of opened charts by Drag'n'Drop
method from the Navigator window.
For an expert Advisor to stop operating, it should be removed from a chart by selecting "Expert
Advisors - Remove" in chart context menu. Operation of Expert Advisors is also affected by the state
of the button "Enable/disable Expert Advisors".
Custom indicators and Expert Advisors work until they are explicitly removed from a chart;
information about attached Expert Advisors and Indicators is saved between client terminal starts.
Scripts are executed once and are deleted automatically upon operation completion or change of the
current chart state, or upon client terminal shutdown. After the restart of the client terminal scripts
are not started, because the information about them is not saved.
Maximum one Expert Advisor, one script and unlimited number of indicators can operate in one chart.
Program Running
Right after a program is attached to a chart, it is uploaded to the client terminal memory, as well as
global variable are initialized. If some global variable of the class type has a constructor, this
constructor will be called during initialization of global variables.
After that the program is waiting for an event from the client terminal. Each mql5-program should has
at least one event-handler, otherwise the loaded program will not be executed. Event handlers have
predefined names, parameters and return types.
Client terminal adds appearing events to the events queue. So events are processed one after another
in accordance to the order they were received. There is an exception for the NewTick event. If the
queue already has such an event or this event is being processed, the new NewTick event is not
enqueued.
Queue of events is limited in size. At queue overflow, old events are removed without being
processed in order to allow the receipt of new events. Therefore, it is recommended to write efficient
event handlers, and it is not recommended to use infinite loops (there is an exception of scripts,
which handle the Start event only).
loading of a template (if the indicator attached to a chart is specified in the template);
change of a profile (if the indicator is attached to one of the profile charts);
change of a symbol and/or timeframe of a chart, to which the indicator is attached;
after the successful recompilation of an indicator, if the indicator was attached to a chart;
change of input parameters of the indicator.
In case the symbol or timeframe of a chart, to which the Expert Advisor is attached, changes,
Expert Advisors are not loaded or unloaded. In this case client terminal subsequently calls OnDeinit
() handlers on the old symbol/timeframe and OnInit() on the new symbol/timeframe (if they are such),
values of global variables and static variables are not reset. All events, which have been received for
the Expert Advisor before the initialization is completed (OnInit() function) are skipped.
Scripts are loaded immediately after they are attached to a chart and unloaded immediately after they
complete their operation. OnInit() and OnDeinit() are not called for scripts.
When a program is unloaded (deleted from a chart) the client terminal performs deinitialization of
global variables and deletes the events queue. In this case deinitialization means reset of all the
string-type variables, deallocation of dynamical array objects and call of their destructors if they are
available.
For a better understanding of the Expert Advisor operation we recommend to compile the code of the
following Expert Advisor and perform actions of load/unload, template change, symbol change,
timeframe change etc:
Example:
//+------------------------------------------------------------------+
//| TestExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
class CTestClass
{
public:
CTestClass() { Print("CTestClass constructor"); }
~CTestClass() { Print("CTestClass destructor"); }
};
CTestClass global;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Print("Initialisation");
//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print("Deinitialisation with reason",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
See also
Client terminal events, Event handlers
Immediately after the client terminal loads a program (an Expert Advisor or custom indicator) and
starts the process of initialization of global variables, the Init event will be sent, which will be
processed by OnInit() event handler, if there is such. This event is also generated after a security
and/or chart timeframe is changed, after a program is recompiled in MetaEditor, after input
parameters are changed from the setup window of an Expert Advisor or a custom indicator. An Expert
Advisor is also initialized after the account is changed. The Init event is not generated for scripts.
Deinit
Before global variables are deinitialized and the program (Expert Advisor or custom indicator) is
unloaded, the client terminal sends the Deinit event to the program. Deinit is also generated when the
client terminal is closed, when a chart is closed, right before the security and/or timeframe is
changed, at a successful program re-compilation, when input parameters are changed, and when
account is changed.
The deinitialization reason can be obtained from the parameter, passed to the OnDeinit() function.
The OnDeinit() function run is restricted to 2.5 seconds. If during this time the function hasn't been
completed, then it is forcibly terminated. The Deinit event is not generated for scripts.
Start
The Start event is a special event for script activation after it is loaded. This event is processed by
OnStart handler. The Start event is not send to Expert Advisors or custom indicators.
NewTick
The NewTick event is generated if there are new quotes, it is processed by OnTick() of Expert
Advisors attached. In case when OnTick function for the previous quote is being processed when a
new quote is received, the new quote will be ignored by an Expert Advisor, because the corresponding
event will not enqueued.
All new quotes that are received while the program is running are ignored until the OnTick() is
completed. After that the function will run only after a new quote is received. The NewTick event is
generated irrespective of whether automated trade is allowed or not ("Allow/prohibit Auto trading"
button). The prohibition of automated trading denotes only that sending of trade requests from an
Expert Advisor is not allowed, while the Expert Advisor keeps working.
The prohibition of automated trading by pressing the appropriate button will not stop the current
execution of the OnTick() function. OnTick() is not started when the window of Expert Advisor
properties is open. The window of properties cannot be opened when the Expert Advisor is runnung.
Calculate
The Calculate event is generated only for indicators right after the Init event is sent and at any
change of price data. It is processed by the OnCalculate function.
Timer
The Timer event is periodically generated by the client terminal for the Expert Advisor that has
activated the timer by the EventSetTimer function. Usually, this function is called by OnInit. Timer
event processing is performed by the OnTimer function. After the operation of the Expert Advisor is
completed, it is necessary to destroy the timer using the EventKillTimer function, which is usually
called in the OnDeinit function.
Trade
The Trade event is generated when a trade operation is completed on a trade server. The Trade event
is handled by the OnTrade() function for the following trade operations:
Tester
The Tester event is generated after testing of an Expert Advisor on history data is over. The event is
handled by the OnTester() function.
ChartEvent
The ChartEvent event is generated by the client terminal when a user is working with a chart:
Also there is a custom event ChartEvent, which can be sent to an Expert Advisor by any mql5-program
by using the EventChartCustom function. The event is processed by the OnChartEvent function.
BookEvent
The BookEvent event is generated by the client terminal after the Depth Of Market is changed; it is
processed by the OnBookEvent function. To start generation of BookEvent for the specified symbol, it
is necessary to subscribe the symbol to this event by using the MarketBookAdd function.
To unsubscribe from BookEvent for a specified symbol, it is necessary to call the MarketBookRelease
function. The BookEvent event is a broadcasting-type event - it means that it is sufficient to
subscribe just one Expert Advisor for this event, and all other Expert Advisors that have the
OnBookEvent event, will receive it. That's why it is necessary to analyse the symbol name, which is
passed to a handler as a parameter.
See also
Resources
Using graphics and sound in MQL5 programs
Programs in MQL5 allow working with sound and graphic files:
PlaySound()
//+------------------------------------------------------------------+
//| the function calls standard OrderSend() and plays a sound |
//+------------------------------------------------------------------+
void OrderSendWithAudio(MqlTradeRequest &request, MqlTradeResult &result)
{
//--- send a request to a server
OrderSend(request,result);
//--- if a request is accepted, play sound Ok.wav
if(result.retcode==TRADE_RETCODE_PLACED) PlaySound("Ok.wav");
//--- if fails, play alarm from file timeout.wav
else PlaySound("timeout.wav");
}
The example shows how to play sounds from files Ok.wav and timeoit.wav, which are included into the
standard terminal package. These files are located in the folder terminal_directory\Sounds. Here
terminal_directory is a folder, from which the MetaTrader 5 Client Terminal is started. The location
of the terminal directory can be found out from an mql5 program in the following way:
You can use sound files not only from the folder terminal_directory\Sounds, but also from any
subfolder located in terminal_data_directory\MQL5. You can find out the location of the terminal
data directory from the terminal menu File - Open terminal data or in using program method:
For example, if the Demo.wav sound file is located in terminal_data_directory\MQL5\Files, then call of
PlaySound() should be written the following way:
Please note that in the comment the path to the file is written using backslash "\", and in the function
"\\" is used.
When specifying the path, always use only the double backslash as a separator, because a single
backslash is a control symbol for the compiler when dealing with constant strings and character
constants in the program source code.
ObjectCreate()
Example of an Expert Advisor, which creates a graphical label (OBJ_BITMAP_LABEL) using the
ObjectCreate() function.
if(!set)
{
PrintFormat("Failed to download image from file %s. Error code %d",dollar,GetLastError(
}
//--- send a command for a chart to refresh so that the button appears immediately without
ChartRedraw(0);
}
else
{
//--- failed to create an object, notify
PrintFormat("Failed to create object OBJ_BITMAP_LABEL. Error code %d",GetLastError());
}
}
//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete an object from a chart
ObjectDelete(0,label_name);
}
Creation and setup of the graphical object named currency_label are carried out in the OnInit()
function. The paths to the graphical files are set in global variables euro and dollar, a double backlash
is used for a separator:
Object OBJ_BITMAP_LABEL is actually a button, which displays one of the two images, depending on
the button state (pressed or unpressed): euro.bmp or dollar.bmp.
The size of the button with a graphical interface is automatically adjusted to the size of the picture.
The image is changed by a left mouse button click on the OBJ_BITMAP_LABEL object ("Disable
selection" must be set in the properties). The OBJ_BITMAP object is created the same way - it is
used for creating the background with a necessary image.
The value of the OBJPROP_BMPFILE property, which is responsible for the appearance of the objects
OBJ_BITMAP and OBJ_BITMAP_LABEL, can be changed dynamically. This allows creating various
interactive user interfaces for mql5 programs.
#resource path_to_resource_file
The #resource command tells the compiler that the resource at the specified path
path_to_resource_file should be included into the executable EX5 file. Thus all the necessary images
and sounds can be located directly in an EX5 file, so that there is no need to transfer separately the
files used in it, if you want to run the program on a different terminal. Any EX5 file can contain
resources, and any EX5 program can use resources from another EX5 program.
The files in format BMP and WAV are automatically compressed before including them to an EX5 file.
This denotes that in addition to the creation of complete programs in MQL5, using resources also
allows to reduce the total size of necessary files when using graphics and sounds, as compared to the
usual way of MQL5 program writing.
#resource "<path_to_resource_file>"
The length of the constant string <path_to_resource_file> must not exceed 63 characters.
The compiler searches for a resource at the specified path in the following order:
if the backslash "\" separator (written as "\\") is placed at the beginning of the path, it searches for
the resource relative to the directory terminal_data_directory\MQL5\,
if there is no backslash, it searches for the resource relative to the location of the source file, in
which the resource is written.
The resource path cannot contain the substrings "..\\" and ":\\".
Use of Resources
Resource name
After a resource is declared using the #resource directive, it can be used in any part of a program.
The name of the resource is its path without a backslash at the beginning of the line, which sets the
path to the resource. To use your own resource in the code, the special sign "::" should be added
before the resource name.
Examples:
It should be noted that when setting images from a resource to the OBJ_BITMAP and
OBJ_BITMAP_LABEL objects, the value of the OBJPROP_BMPFILE property cannot be modified
manually. For example, for creating OBJ_BITMAP_LABEL we use resources euro.bmp and dollar.bmp.
When viewing the properties of this object, we'll see that the properties BitMap File (On) and BitMap
File (Off) are dimmed and cannot be change manually:
There is another advantage of resource using – in any mql5 program, resources of another EX5 file can
be used. Thus the resources from one EX5 file can be used in many other mql5 programs.
In order to use a resource name from another file, it should be specified as <path_EX5_file_name>::
<resource_name>. For example, suppose the Draw_Triangles_Script.mq5 script contains a resource to
an image in the file triangle.bmp:
#resource "\\Files\\triangle.bmp"
Then its name, for using in the script itself, will look like "Files\triangle.bmp", and in order to use it,
"::" should be added to the resource name.
In order to use the same resource from another program, e.g. from an Expert Advisor, we need to add
to the resource name the path to the EX5 file relative to terminal_data_directory\MQL5\ and the
name of the script's EX5 file - Draw_Triangles_Script.ex5. Suppose the script is located in the
standard folder terminal_data_directory\MQL5\Scripts\, then the call should be written the following
way:
If the path to the executable file is not specified when calling the resource from another EX5, the
executable file is searched for in the same folder that contains the program that calls the resource.
This means that if an Expert Advisor calls a resource from Draw_Triangles_Script.ex5 without
specification of the path, like this:
then the file will be searched for in the folder terminal_data_directory\MQL5\Experts\, if the Expert
Advisor is located in terminal_data_directory\MQL5\Experts\.
See also
PlaySound(), ObjectSetInteger(), ChartApplyTemplate(), File Functions
It is not recommended to use the fully specified name of the module to be loaded like Drive:
\Directory\FileName.Ext. The MQL5 libraries are loaded from the terminal_dir\MQL5\Libraries folder.
If the library hasn't been found, then the client terminal performs an attempt to load it from
terminal_dir\experts folder.
The system libraries (DLL) are loaded by the operating system rules. If the library is already loaded
(for example, another Expert Advisor, and even from another client terminal, running in parallel),
then it uses requests to the library already loaded. Otherwise, it performs a search in the following
sequence:
1. Directory, from which the module importing dll was started. The module here is an Expert Advisor,
a script, an indicator or EX5 library;
2. Directory terminal_data_directory\MQL5\Libraries (TERMINAL_DATA_PATH\MQL5\Libraries);
3. Directory, from which the MetaTrader 5 client terminal was started;
4. System directory;
5. Windows directory;
6. Current directory;
7. Directories listed in the PATH system variable.
If the DLL library uses another DLL in its work, the first one cannot be loaded in case when there is no
second DLL.
Before an Expert Advisor (script, indicator) is loaded, a common list of all EX5 library modules is
formed. It's going to be usd both from a loaded Expert Advisor (script, indicator) and from libraries of
this list. Thus the one-time loading of many times used EX5 library modules is needed. Libraries use
predefined variables of the Expert Advisor (script, indicator) they were called by.
1. Directory, path to which is set relative to the directory of the Expert Advisor (script, indicator) that
imports EX5);
2. Directory terminal_directory\MQL5\Libraries;
3. Directory MQL5\Libraries in the common directory of all MetaTrader 5 client terminals
(Common\MQL5\Libraries).
Functions imported DLL into a mql5-program must ensure the Windows API calls agreement. To ensure
such an agreement, in the source text of programs written in C or C++, use the keyword __stdcall,
which is specific to the Microsoft(r) compilers. This agreement is characterized by the following:
caller (in our case it is a mq5-program) should "see" a prototype of a function called (imported from
the DLL), in order to properly combine parameters to a stack;
caller (in our case it is a mql5-program) puts parameters to the stack in a reverse order, from right
to left - in this order an imported function reads parameters passed to it;
parameters are passed by value, except those explicitly passed by reference (in our case lines)
an imported function cleans the stack independently by reading parameters passed to it.
When describing the prototype of an imported function, default parameters can be used.
If the corresponding library is unable to load, or there is a prohibition on the DLL use, or the imported
function is not found - the Expert Advisor stops its operation with the appropriate message "Expert
Advisor stopped" in the Journal (log file). In this case the Expert Advisor will not run until it is
reinitialized. An Expert Advisor can be reinitialized as a result of recompilation or after the table of
its properties is opened and OK is pressed.
Passing Parameters
All parameters of simple types are passed by values unless it is explicitly indicated that they are
passed by reference. When a string is passed, the address of the buffer of the copied string is passed;
if a string is passed by reference, the address of the buffer of this string without copying it is passed
to the function imported from DLL.
Structures that contain dynamic arrays, strings, classes, other complex structures, as well as static or
dynamic arrays of the enumerated objects, can't be passed as a parameter to an imported function.
When passing an array to DLL, the address of the beginning of the data buffer is always passed
(irrespective of the AS_SERIES flag). A function inside a DLL knows nothing about the AS_SERIES flag,
the passed array is a static array of an undefined length; an additional parameter should be used for
specifying the array size.
Runtime Errors
The executing subsystem of the client terminal has an opportunity to save the error code in case any
occurs during a mql5-program run. There is a a predefined variable _LastError for each executable
mql5 program.
Before starting the OnInit function, the _LastError variable is reset. In case an erroneous situations
occurs during calculations or in the process of internal function calls, the _LastError variable accepts a
corresponding error code. The value stored in this variable can be obtained by using the GetLastError
() function.
There are several critical errors, appearing which a program is terminated immediately :
division by zero;
going beyond array ranges;
using an incorrect object pointer;
Values of predefined variables are set by the client terminal before a mql5-program is started.
Predefined variables are constant and cannot be changed from a mql5-program. As exception, there is
a special variable _LastError, which can be reset to 0 by the ResetLastError function.
Variable Value
Libraries are used by variables of the program they were called by.
int _Digits
The _Digits variable stores number of digits after a decimal point, which defines the price accuracy of
the symbol of the current chart.
double _Point
The _Point variable contains the point size of the current symbol in the quote currency.
int _LastError
The _LastError variable contains code of the last error, that occurred during the mql5-program run. Its
value can be reset to zero by ResetLastError().
To obtain the code of the last error, you may also use the GetLastError() function.
int _Period
The _Period variable contains the value of the timeframe of the current chart.
See also
bool _StopFlag
The _StopFlag variable contains the flag of the mql5-program stop. When the client terminal is trying
to stop the program, it sets the _StopFlag variable to true.
To check the state of the _StopFlag you may also use the IsStopped() function.
string _Symbol
The _Symbol variable contains the symbol name of the current chart.
int _UninitReason
The _UninitReason variable contains the code of the program uninitialization reason.
Common Functions
General-purpose functions not included into any specialized group are listed here.
Function Action
Alert
Displays a message in a separate window.
void Alert(
argument, // first value
... // other values
);
Parameters
argument
[in] Any values, separated by commas. To separate the information output in several lines you
can use the line feed character "\n" or "\r\n". The number of parameters can not exceed 64.
Return Value
No return value.
Note
Arrays can't be passed to the Alert() function. Arrays should be output elementwise. Data of the
double type are output with 8 digits after the decimal point, data of the float type are displayed
with 5 digits after the decimal point. To derive the real numbers with a different precision or in a
scientific format, use DoubleToString().
Data of bool the type are output as "true" or "false" strings. Dates are output as YYYY.MM.DD HH:
MI:SS. To display a date in another format use TimeToString(). Data of the color type are output
either as an R,G,B string or as a color name, if the color is present in a color set.
CheckPointer
The function returns the type of the object pointer.
ENUM_POINTER_TYPE CheckPointer(
object* anyobject // object pointer
);
Parameters
anyobject
[in] Object pointer.
Return value
Note
An attempt to call an incorrect pointer results in the critical termination of a program. That's why
it's necessary to call the CheckPointer function before using a pointer. A pointer can be incorrect in
the following cases:
This function can be used for checking pointer validity. A non-zero value warranties that the pointer
can be used for accessing.
Example:
//+------------------------------------------------------------------+
//| delete list by deleting its elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer for working in the loop
CItem* item;
//--- go through loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
Comment
This function outputs a comment defined by a user in the top left corner of a chart.
void Comment(
argument, // first value
... // next values
);
Parameters
...
[in] Any values, separated by commas. To delimit output information into several lines, a line
break symbol "\n" or "\r\n" is used. Number of parameters cannot exceed 64. Total length of the
input comment (including invisible symbols) cannot exceed 2045 characters (excess symbols will be
cut out during output).
Return Value
No return value
Note
Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be
output either in traditional or in scientific format, depending on what entry will be more compact.
Data of float type are output with 5 digits after a decimal point. To output real numbers with
another accuracy or in a predefined format, use the DoubleToString() function.
Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS.
To show data in another format, use TimeToString(). Data of color type are returned either as R,G,
B line or as a color name, if this color is present in the color set.
Example:
void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
//--- Output values in three lines
Comment(StringFormat("Show prices\nAsk = %G\nBid = %G\nSpread = %d",Ask,Bid,Spread));
}
See also
ChartSetString, ChartGetString
DebugBreak
It is a program breakpoint in debugging.
void DebugBreak();
Return Value
No return value.
Note
Execution of an mql5 program is broken only if a program is started in a debugging mode. The
function can be used for viewing values fo variables and/or for further step-by-step execution.
ExpertRemove
The function stops an Expert Advisor and unloads it from a chart.
void ExpertRemove();
Returned value
No return value.
Note
The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag to stop the
EA operation is set. That is, any next event won't be processed, OnDeinit() will be called and the
Expert Advisor will be unloaded and removed from the chart.
Example:
//+------------------------------------------------------------------+
//| Test_ExpertRemove.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
input int ticks_to_close=20;// number of ticks before EA unload
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print(TimeCurrent(),": " ,__FUNCTION__," reason code = ",reason);
//--- "clear" comment
Comment("");
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static int tick_counter=0;
//---
tick_counter++;
Comment("\nBefore unloading expert advisor ",__FILE__," left",
(ticks_to_close-tick_counter)," ticks");
//--- before
if(tick_counter>=ticks_to_close)
{
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}
Print("tick_counter =",tick_counter);
//---
}
//+------------------------------------------------------------------+
See also
GetPointer
The function returns the object pointer.
void* GetPointer(
any_class anyobject // object of any class
);
Parameters
anyobject
[in] Object of any class.
Return Value
Note
Only class objects have pointers. Instances of structures and simple-type variables can't have
pointers. The class object not created using the new() operator, but, e.g., automatically created in
the array of objects, still has a pointer. But this pointer will be of the automatic type
POINTER_AUTOMATIC, therefore the delete() operator can't be applied to it. Aside from that, the
type pointer doesn't differ from dynamic pointers of the POINTER_AUTOMATIC type.
Since variables of structure types and simple types do not have pointers, it's prohibited to apply the
GetPointer() function to them. It's also prohibited to pass the pointer as a function argument. In all
these cases the compiler will notify of an error.
An attempt to call an incorrect pointer causes the critical termination of a program. That's why the
CheckPointer() function should be called prior to using a pointer. A pointer can be incorrect in the
following cases:
This function can be used to check the validity of a pointer. A non-zero value guarantees, that the
pointer can be used for accessing.
Example:
//+------------------------------------------------------------------+
//| Check_GetPointer.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| class implementing the list element |
//+------------------------------------------------------------------+
class CItem
{
int m_id;
string m_comment;
CItem* m_next;
public:
CItem() { m_id=0; m_comment=NULL; m_next=NULL; }
~CItem() { Print("Destructor of ",m_id,
(CheckPointer(GetPointer(this))==POINTER_DYNAMIC)?
"dynamic":"non-dynamic"); }
void Initialize(int id,string comm) { m_id=id; m_comment=comm; }
void PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }
int Identifier() { return(m_id); }
CItem* Next() {return(m_next); }
void Next(CItem *item) { m_next=item; }
};
//+------------------------------------------------------------------+
//| simplest class of the list |
//+------------------------------------------------------------------+
class CMyList
{
CItem* m_items;
public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool InsertToBegin(CItem* item);
void Destroy();
};
//+------------------------------------------------------------------+
//| inserting list element at the beginning |
//+------------------------------------------------------------------+
bool CMyList::InsertToBegin(CItem* item)
{
if(CheckPointer(item)==POINTER_INVALID) return(false);
//---
item.Next(m_items);
m_items=item;
//---
return(true);
}
//+------------------------------------------------------------------+
//| deleting the list by deleting elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer to work in a loop
CItem* item;
//--- go through the loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CMyList list;
CItem items[10];
CItem* item;
//--- create and add into the list a dynamic object pointer
item=new CItem;
if(item!=NULL)
{
item.Initialize(100,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- add automatic pointers into the list
for(int i=0; i<10; i++)
{
items[i].Initialize(i,"automatic");
items[i].PrintMe();
item=GetPointer(items[i]);
if(CheckPointer(item)!=POINTER_INVALID)
list.InsertToBegin(item);
}
//--- add one more dynamic object pointer at the list beginning
item=new CItem;
if(item!=NULL)
{
item.Initialize(200,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- delete all the list elements
list.Destroy();
//--- all the list elements will be deleted after the script is over
//--- see the Experts tab in the terminal
}
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
GetTickCount
The GetTickCount() function returns the number of milliseconds that elapsed since the system start.
uint GetTickCount();
Return Value
Note
Counter is limited by the restrictions of the system timer. Time is stored as an unsigned integer, so
it's overfilled every 49.7 if a computer works uninterruptedly.
MessageBox
It creates and shows a message box and manages it. A message box contains a message and header,
any combination of predefined signs and command buttons.
int MessageBox(
string text, // message text
string caption=NULL, // box header
int flags=0 // defines set of buttons in the box
);
Parameters
text
[in] Text, containing message to output.
caption=NULL
[in] Optional text to be displayed in the box header. If the parameter is empty, Expert Advisor
name is shown in the box header.
flags=0
[in] Optional flags defining appearance and behavior of a message box. Flags can be a
combination of a special group of flags.
Return Value
If the function is successfully performed, the returned value is one of values of MessageBox() return
codes.
Note
The function can't be called from custom indicators, because indicators are executed in the
interface thread and shouldn't slow down it.
PeriodSeconds
This function returns number of seconds in a period.
int PeriodSeconds(
ENUM_TIMEFRAMES period=PERIOD_CURRENT // chart period
);
Parameters
period=PERIOD_CURRENT
[in] Value of a chart period from the enumeration ENUM_TIMEFRAMES. If the parameter isn't
specified, it returns the number of seconds of the current chart period, at which the program
runs.
Return Value
See also
PlaySound
It plays a sound file.
bool PlaySound(
string filename // file name
);
Parameters
filename
[in] Path to a sound file.
Return Value
Note
The file must be located in terminal_directory\Sounds ot its sub-directory. Only WAV files are
played.
See also
Resources
Print
It enters a message in the Expert advisor log. parameters can be of any type..
void Print(
argument, // first value
... // next values
);
Parameters
...
[in] Any values separated by commas. Number of parameters can't exceed 64.
Note
Arrays cannot be passed to the Print() function. Arrays must be input element-by-element.
Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be
output either in traditional or in scientific format, depending on what entry will be more compact.
Data of float type are output with 5 digits after a decimal point. To output real numbers with
another accuracy or in a predefined format, use the DoubleToString() function.
Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS.
To show data in another format, use TimeToString(). Data of color type are returned either as R,G,
B line or as a color name, if this color is present in the color set.
Example:
See also
PrintFormat, StringFormat
PrintFormat
It formats and enters sets of symbols and values in the Expert Advisor log in accordance with a preset
format.
void PrintFormat(
string format_string, // format line
... // values of simple types
);
Parameters
format_string
[in] A format line consists of simple symbols, and if the format line is followed by arguments, it
also contains format specifications.
...
[in] Any values of simple types separated by commas. Total number of parameters can't exceed
64 including the format line.
Return Value
String.
Note
If the format line is followed by parameters, this line must contain format specifications that
denote output format of these parameters. Specification of format always starts with the percent
sign (%).
A format line is read from left to right. When the first format specification is met (if there is any),
the value of the first parameter after the format line is transformed and output according to the
preset specification. The second format specification calls transformation and output of the second
parameter, and so on till the format line end.
Each field of the format specification is either a simple symbol, or a number denoting a simple
format option. The simplest format specification contains only the percent sign (%) and a symbol
defining the type of the output parameter (for example, %s). If you need to output the percent sign
in the format line, use the format specification %%.
flags
set width
+ (plus) Output of the + or - sign for The sign is shown only of the
values of sign types value is negative
width
A non-negative decimal number that sets the minimal number of output symbols of the formatted
value. If the number of output symbols is less than the set width, the corresponding number of
spaces is added from the left or right depending on the alignment (flag –). If there is flag zero (0),
the corresponding number of zeroes is added before the output value. If the number of output
values is larger than the the preset width, the output value is never cut off.
If an asterisk (*) is specified as width, value of int type must be indicated in the corresponding
place of the list of passed parameters. It will be used for specifying width of the output value.
precision
A non-negative decimal number that sets the output accuracy - number of digits after a decimal
point. As distinct from width specification, accuracy specification can cut off the part of fractional
type with or without rounding.
c, C Not used
h | l | ll | I32 | I64
short h d, i, o, x, or X
ushort h o, u, x, or X
int I32 d, i, o, x, or X
uint I32 o, u, x, or X
long I64 d, i, o, x, or X
ulong I64 o, u, x, or X
type
Example:
See also
StringFormat, DoubleToString, Real types (double, float)
ResetLastError
Sets the value of the predefined variable _LastError into zero.
void ResetLastError();
Return Value
No return value.
Note
It should be noted that the GetLastError() function doesn't zero _LastError variable. Usually
ResetLastError() is called befor function call, after which error appearance is checked.
SetUserError
Sets the predefined variable _LastError into the value equal to ERR_USER_ERROR_FIRST + user_error
void SetUserError(
ushort user_error, // error number
);
Parameters
user_error
[in] Error number set by a user.
Return Value
No return value.
Note
After an error has been set using the SetUserError(user_error) function, GetLastError() returns
value equal to ERR_USER_ERROR_FIRST + user_error.
Example:
void OnStart()
{
//--- set error number 65537=(ERR_USER_ERROR_FIRST +1)
SetUserError(1);
//--- get last error code
Print("GetLastError = ",GetLastError());
/*
Result
GetLastError = 65537
*/
}
SendFTP
Sends a file at the address, specified in the setting window of the "Publisher" tab.
bool SendFTP(
string filename, // file to send by ftp
string ftp_path=NULL // file to upload on ftp server
);
Parameters
filename
[in] Name of sent file.
ftp_path=NULL
[in] FTP catalog. If a directory is not specified, directory described in settings is usesd.
Return Value
Note
Sent file must be located in the folder terminal_directory\MQL5\files or its subfolders. Sending isn't
performed if FTP address and/or access password are not specified in settings.
SendMail
Sends an email at the address specified in the settings window of the "Mailbox" tab.
bool SendMail(
string subject, // header
string some_text // email text
);
Parameters
subject
[in] Email header.
some_text
[in] Email body.
Return Value
Note
Sending can be prohibited in settings, email address can be not specified. For the error information
call GetLastError().
Sleep
The function suspends execution of the current Expert Advisor or script within a specified interval.
void Sleep(
int milliseconds // interval
);
Parameters
milliseconds
[in] Delay interval in milliseconds.
Return Value
No return value.
Note
The Sleep() function can't be called for custom indicators, because indicators are executed in the
interface thread and must not slow down it. The function has the built-in check of EA halt flag every
0.1 seconds.
TerminalClose
The function commands the terminal to complete operation.
bool TerminalClose(
int ret_code // closing code of the client terminal
);
Parameters
ret_code
[in] Return code, returned by the process of the client terminal at the operation completion.
Return Value
Note
The TerminalClose() function does not stop the terminal immediately, it just commands the
terminal to complete its operation.
The code of an Expert Advisor that called TerminalClose() must have all arrangements for the
immediate completion (e.g. all previously opened files must be closed in the normal mode). Call of
this function must be followed by the return operator.
The ret_code parameter allows indicating the necessary return code for analyzing reasons of the
program termination of the terminal operation when starting it from the command prompt.
Example:
MqlTick tick;
double distance;
//---
SymbolInfoTick(_Symbol,tick);
tick_counter++;
if(first_bid==0.0)
{
launch_time=tick.time;
first_bid=tick.bid;
Print("first_bid =",first_bid);
return;
}
//--- price distance in pips
distance=(tick.bid-first_bid)/_Point;
//--- show a notification to track the EA operation
string comm="From the moment of start:\r\n\x25CF elapsed seconds: "+
IntegerToString(tick.time-launch_time)+" ;"+
"\r\n\x25CF ticks received: "+(string)tick_counter+" ;"+
"\r\n\x25CF price went in points: "+StringFormat("%G",distance);
Comment(comm);
//--- section for checking condition to close the terminal
if(tick_counter>=tiks_before)
TerminalClose(0); // exit by tick counter
if(distance>pips_to_go)
TerminalClose(1); // go up by the number of pips equal to pips_to_go
if(distance<-pips_to_go)
TerminalClose(-1); // go down by the number of pips equal to pips_to_go
if(tick.time-launch_time>seconds_st)
TerminalClose(100); // termination by timeout
//---
}
See also
Program running, Execution errors, Reasons for deinitialization
TesterStatistics
The function returns the value of the specified statistical parameter calculated based on testing
results
double TesterStatistics(
ENUM_STATISTICS statistic_id // ID
);
Parameters
statistic_id
[in] The ID of he statistical parameter from the ENUM_STATISTICS enumeration.
Return Value
Note
The function can be called inside OnTester() or OnDeinit() in the tester. In other cases the result is
undefined.
TesterWithdrawal
The special function to emulate the operation of money withdrawal in the process of testing. Can be
used in some asset management systems.
bool TesterWithdrawal(
double money // the sum to withdraw
);
Parameters
money
[in] The sum of money that we need to withdraw (in the deposit currency).
Return Value
ZeroMemory
The function resets a variable passed to it by reference.
void ZeroMemory(
void & variable // reset variable
);
Parameters
variable
[in] [out] Variable passed by reference, you want to reset (initialize by zero values).
Return Value
No return value.
Note
If the function parameter is a string, the call will be equivalent to indicating NULL as its value.
For simple types and their arrays, as well as for structures/classes consisting of such types, this is a
simple reset.
For objects containing strings and dynamic arrays, ZeroMemory() is called for each element.
For any arrays not protected by the const modifier, this is the zeroing of all elements.
For arrays of complex objects, ZeroMemory() is called for each element.
Function Action
ArrayBsearch
The function searches for a specified value in a one-dimension numeric array.
int ArrayBsearch(
double array[], // array for search
double searched_value // what is searched for
);
int ArrayBsearch(
float array[], // array for search
float searched_value // what is searched for
);
int ArrayBsearch(
long array[], // array for search
long searched_value // what is searched for
);
int ArrayBsearch(
int array[], // array for search
int searched_value // what is searched for
);
int ArrayBsearch(
short array[], // array for search
short searched_value // what is searched for
);
int ArrayBsearch(
char array[], // array for search
char searched_value // what is searched for
);
Parameters
array[]
[in] Numeric array for search.
searched_value
[in] Value for search.
Return Value
The function returns index of a found element. If the wanted value isn't found, the function returns
the index of an element nearest in value.
Note
Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort() function.
ArrayCopy
It copies an array into another one.
int ArrayCopy(
void dst_array[], // destination array
void src_array[], // source array
int dst_start=0, // index starting from which write into destination array
int src_start=0, // first index of a source array
int cnt=WHOLE_ARRAY // number of elements
);
Parameters
dst_array[]
[out] Destination array
src_array[]
[in] Source array
dst_start=0
[in] Starting index fro the destination array. By default, start index is 0.
src_start=0
[in] Starting index for the source array. By default, start index is 0.
cnt=-1
[in] Number of elements that should be copied. By default, the whole array is copied
(cnt=WHOLE_ARRAY).
Return Value
Note
If cnt<0 or cnt>src_size-src_start, all the remaining array part is copied. Arrays are copied from left
to right. For series arrays, the starting position is correctly defined adjusted for copying from left
to right. If an array is copied to itself, the result is undefined.
If arrays are of different types, during copying it tries to transform each element of a source array
into the type of the destination array. A string array can be copied into a string array only. Array of
classes and structures containing objects that require initialization aren't copied. An array of
structures can be copied into an array of the same type only.
ArrayFree
It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.
void ArrayFree(
void array[] // array
);
Parameters
array[]
[in] Dynamic array.
Return Value
No return value.
ArrayGetAsSeries
It checks direction of an array index.
bool ArrayGetAsSeries(
void array // array for checking
);
Parameters
array
[in] Checked array.
Return Value
Returns true, if the specified array has the AS_SERIES flag set, i.e. access to the array is performed
back to front as in timeseries. A timeseries differs from a usual array in that the indexing of
timeseries elements is performed from its end to beginning (from the newest data to old).
Note
To check whether an array belongs to timeseries, use the ArrayIsSeries() function. Arrays of price
data passed as input parameters into the OnCalculate() function do not obligatorily have the
indexing direction the same as in timeseries. The necessary indexing direction can be set using the
ArraySetAsSeries() function.
See also
Access to timeseries, ArraySetAsSeries
ArrayInitialize
The function initializes a numeric array by a preset value.
void ArrayInitialize(
double array[], // initialized array
double value // value that will be set
);
Parameters
array[]
[out] Numeric array that should be initialized.
value
[in] New value that should be set to all array elements.
Return Value
No return value.
Note
The ArrayResize() function allows to set size of an array with a reserve for further expansion
without the physical relocation of memory. It is implemented for the better performance, because
the operations of memory relocation are reasonably slow.
Initialization of the array using ArrayInitialize(array, init_val) doesn't mean the initialization with
the same value of reserve elements allocated for this array. At further expanding of the array using
the ArrayResize() function, the elements will be added at the end of the array, their values will be
undefined and in most cases will not be equal to init_value.
Example:
void OnStart()
{
//--- dynamic array
double array[];
//--- let's set the array size for 100 elements and reserve a buffer for another 10 elements
ArrayResize(array,100,10);
//--- initialize the array elements with EMPTY_VALUE=DBL_MAX value
ArrayInitialize(array,EMPTY_VALUE);
Print("Values of 10 last elements after initialization");
for(int i=90;i<100;i++) printf("array[%d] = %G",i,array[i]);
//--- expand the array by 5 elements
ArrayResize(array,105);
Print("Values of 10 last elements after ArrayResize(array,105)");
//--- values of 5 last elements are obtained from reserve buffer
for(int i=95;i<105;i++) printf("array[%d] = %G",i,array[i]);
}
ArrayIsDynamic
The function checks whether an array is dynamic.
bool ArrayIsDynamic(
void array[] // checked array
);
Parameters
array[]
[in] Checked array.
Return Value
See also
Access to timeseries and indicators
ArrayIsSeries
The function checks whether an array is a timeseries.
bool ArrayIsSeries(
void array[] // checked array
);
Parameters
array[]
[in] Checked array.
Return Value
It returns true, if a checked array is an array timeseries, otherwise it returns false. Arrays passed
as a parameter to the OnCalculate() function must be checked for the order of accessing the array
elements by ArrayGetAsSeries().
Example:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double Label1Buffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
See also
Access to timeseries and indicators
ArrayMaximum
The function searches a maximal element in a one-dimension numeric array.
int ArrayMaximum(
double array[], // array for search
int start=0 // index to start checking with
int count=WHOLE_ARRAY, // number of checked elements
);
Parameters
array[]
[in] A numeric array, in which search is made.
start=0
[in] Index to start checking with.
count=WHOLE_ARRAY
[in] Number of elements for search. By default, searches in the entire array (cnt=WHOLE_ARRAY
).
Return Value
The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
ArrayMinimum
The function searches a minimal element in a one-dimension numeric array.
int ArrayMinimum(
double array[], // array for search
int start=0 // index to start checking with
int count=WHOLE_ARRAY, // number of checked elements
);
Parameters
array[]
[in] A numeric array, in which search is made.
start=0
[in] Index to start checking with.
count=WHOLE_ARRAY
[in] Number of elements for search. By default, searches in the entire array (cnt=WHOLE_ARRAY
).
Return Value
The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
ArrayRange
The function returns the number of elements in a selected array dimension.
int ArrayRange(
void array[], // array for check
int rank_index // number of dimension
);
Parameters
array[]
[in] Checked array.
rank_index
[in] Index of dimension.
Return Value
Note
Since indexes are zero-based, the size of dimension is 1 greater than the largest index.
ArrayResize
The function sets a new size for the first dimension
int ArrayResize(
void array[], // array passed by reference
int new_size, // new array size
int reserve_size=0 // reserve size value (excess)
);
Parameters
array[]
[out] Array for changing sizes.
new_size
[in] New size for the first dimension.
reserve_size=0
[in] Distributed size to get reserve.
Return Value
If executed successfully, it returns count of all elements contained in the array after resizing,
otherwise, returns -1, and array is not resized.
Note
During memory allocation the reserve_size parameter is taken into account. If this parameter is
specified, it sets the size of additional memory for the array. Re-calls of ArrayResize do not result
in physical re-allocation of memory, only the first array dimension is resized within the reserved
memory.
The function can be applied only to dynamic arrays. Please note that you can't change the size for
dynamic arrays set as indicator buffers by the function SetIndexBuffer(). For indicator buffers, all
operations of size changes are performed by the executing sub-system of the terminal.
See also
ArrayInitialize
ArraySetAsSeries
The function sets the AS_SERIES flag to a selected object of a dynamic array, and elements will be
indexed like in timeseries.
bool ArraySetAsSeries(
void array[], // array by reference
bool set // true denotes reverse order of indexing
);
Parameters
array[]
[in][out] Numeric array to set.
set
[in] Array indexing direction.
Return Value
Note
The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays (arrays, whose size in
square brackets is preset already on the compilation stage). Indexing in timeseries differs from a
common array in that the elements of timeseries are indexed from the end towards the beginning
(from the newest to oldest data).
//+------------------------------------------------------------------+
//| BarNumber.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
See also
ArraySize
The function returns the number of elements of a selected array.
int ArraySize(
void array[] // checked array
);
Parameters
array[]
[in] Array of any type.
Return Value
Note
For a one-dimensional array, the value to be returned by the ArraySize is equal to that of
ArrayRange(array,0).
ArraySort
The function sorts numeric arrays in ascending order from left to right.
bool ArraySort(
number& array[] // array for sorting
);
Parameters
array[]
[in][out] Numeric array for sorting.
Return Value
Note
Conversion Functions
This is a group of functions that provide conversion of data from one format into another.
The NormalizeDouble() function must be specially noted as it provides the necessary accuracy of the
price presentation. In trading operations, no unnormalized prices may be used if their accuracy even a
digit exceeds that required by the trade server.
Function Action
See also
Use of a Codepage
CharToString
Converting a symbol code into a one-character string.
string CharToString(
uchar char_code // numeric code of symbol
);
Parameters
char_code
[in] Code of ANSI symbol.
Return Value
CharArrayToString
It copies and converts part of array of uchar type into a returned string.
string CharArrayToString(
uchar array[], // array
int start=0, // starting position in the array
int count=-1 // number of sumbols
uint codepage=CP_ACP // code page
);
Parameters
array[]
[in] Array of uchar type.
start=0
[in] Position from which copying starts. by default 0 is used.
count=-1
[in] Number of array elements for copying. Defines the length of a resulting string. Default value
is -1, which means copying up to the array end, or till terminal 0.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide appropriate constants.
Return Value
String.
See also
Use of a Codepage
ColorToString
It converts color value into string of "R,G,B" form.
string ColorToString(
color color_value, // color value
bool color_name // show color name or not
);
Parameters
color_value
[in] Color value in color type variable.
color_name
[in] Sign of the necessity to return color name, if color name is identical to one of predefined
color constants.
Return Value
String presentation of color as "R,G,B", where R, G and B are decimal constants from 0 to 255
converted into a string. If the color_name=true parameter is set, it will try to convert color value
into color name.
Example:
DoubleToString
Converting numeric value into text string.
string DoubleToString(
double value, // number
int digits=8 // number of digits after decimal point
);
Parameters
value
[in] Value with a floating point.
digits
[in] Accuracy format. If the digits value is in the range between 0 and 16, a string presentation of
a number with the specified number of digits after the point will be obtained. If the digits value is
in the range between -1 and -16, a string representation of a number in the scientific format with
the specified number of digits after the decimal point will be obtained. In all other cases the string
value will contain 8 digits after the decimal point.
Return Value
Example:
See also
NormalizeDouble, StringToDouble
EnumToString
Converting an enumeration value of any type to a text form.
string EnumToString(
any_enum value // any type enumeration value
);
Parameters
value
[in] Any type enumeration value.
Return Value
A string with a text representation of the enumeration. To get the error message call the
GetLastError() function.
Note
The function can set the following error values in the _LastError variable:
ERR_INTERNAL_ERROR – error of the execution environment
ERR_NOT_ENOUGH_MEMORY – not enough memory to complete the operation
ERR_INVALID_PARAMETER – can't allow the name of the enumeration value
Example:
//--- set the time interval equal to one year (12 months))
period=year;
Print(EnumToString(period)+"="+IntegerToString(period));
// Result:
// month=1
// quarter=3
// year=12
// ORDER_TYPE_BUY=0
// ENUM_ORDER_TYPE::-1=-1
}
See also
Enumerations, Input variables
IntegerToString
This function converting value of integer type into a string of a specified length and returns the
obtained string.
string IntegerToString(
long number, // number
int str_len=0, // length of result string
ushort fill_symbol=' ' // filler
);
Parameters
number
[in] Number for conversion.
str_len=0
[in] String length. If the resulting string length is larger than the specified one, the string is not
cut off. If it is smaller, filler symbols will be added to the left.
fill_symbol=' '
[in] Filler symbol. By default it is a space.
Return Value
String.
ShortToString
It converts the symbol code (unicode) into one-symbol string and returns resulting string.
string ShortToString(
ushort symbol_code // symbol
);
Parameters
symbol_code
[in] Symbol code. Instead of a symbol code you can use literal string containing a symbol or a
literal string with 2-byte hexadecimal code corresponding to the symbol from the Unicode table.
Return Value
String.
ShortArrayToString
It copies part of array into a returned string.
string ShortArrayToString(
ushort array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);
Parameters
array[]
[in] Array of ushort type (analog of wchar_t type).
start=0
[in] Position, from which copying starts, Default - 0.
count=-1
[in] Number of array elements to copy. Defines the length of a resulting string. Default value is -
1, which means copying up to the array end, or till terminal 0.
Return Value
String.
TimeToString
Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy.mm.dd
hh:mi" format.
string TimeToString(
datetime value, // number
int mode=TIME_DATE|TIME_MINUTES // output format
);
Parameters
value
[in] Time in seconds from 00:00 1970/01/01.
mode=TIME_DATE|TIME_MINUTES
[in] Additional data input mode. Can be one or combined flag: TIME_DATE gets result as "yyyy.
mm.dd", TIME_MINUTES gets result as "hh:mi", TIME_SECONDS gets results as "hh:mi:ss".
Return Value
String.
NormalizeDouble
Rounding floating point number to a specified accuracy.
double NormalizeDouble(
double value, // normalized number
int digits // number of digits after decimal point
);
Parameters
value
[in] Value with a floating point.
digits
[in] Accuracy format, number of digits after point (0-8).
Return Value
Note
Calculated values of StopLoss, TakeProfit, and values of open prices for pending orders must be
normalized with the accuracy, the value of which can be obtained by Digits().
Example:
double pi=M_PI;
Print("pi = ",DoubleToString(pi,16));
double pi_3=NormalizeDouble(M_PI,3);
Print("NormalizeDouble(pi,3) = ",DoubleToString(pi_3,16))
;
double pi_8=NormalizeDouble(M_PI,8);
Print("NormalizeDouble(pi,8) = ",DoubleToString(pi_8,16));
double pi_0=NormalizeDouble(M_PI,0);
Print("NormalizeDouble(pi,0) = ",DoubleToString(pi_0,16));
/*
Result:
pi= 3.1415926535897931
NormalizeDouble(pi,3)= 3.1419999999999999
NormalizeDouble(pi,8)= 3.1415926499999998
NormalizeDouble(pi,0)= 3.0000000000000000
*/
See also
DoubleToString, Real types (double, float), Reduction of types,
StringToCharArray
Symbol-wise copies a string converted from Unicode to ANSI, to a selected place of array of uchar
type. It returns the number of copied elements.
int StringToCharArray(
string text_string, // source string
uchar& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
uint codepage=CP_ACP // code page
);
Parameters
text_string
[in] String to copy.
array[]
[out] Array of uchar type.
start=0
[in] Position from which copying starts. Default - 0.
count=-1
[in] Number of array elements to copy. Defines length of a resulting string. Default value is -1,
which means copying up to the array end, or till terminal 0. Terminal 0 will also be copied to the
recipient array, in this case the size of a dynamic array can be increased if necessary to the size
of the string. If the size of the dynamic array exceeds the length of the line, the size of the array
will not be reduced.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide appropriate constants.
Return Value
See also
Use of a Codepage
StringToColor
Converting "R,G,B" string or string with color name into color type value.
color StringToColor(
string color_string // string representation of color
);
Parameters
color_string
[in] String representation of a color of "R,G,B" type or name of one of predefined Web-colors.
Return Value
Color value.
Example:
color str_color=StringToColor("0,127,0");
Print(str_color);
Print((string)str_color);
//--- change color a little
str_color=StringToColor("0,128,0");
Print(str_color);
Print((string)str_color);
StringToDouble
The function converts string containing a symbol representation of number into number of double
type.
double StringToDouble(
string value // string
);
Parameters
value
[in] String containing a symbol representation of a number.
Return Value
StringToInteger
The function converts string containing a symbol representation of number into number of int
(integer) type.
long StringToInteger(
string value // string
);
Parameters
value
[in] String containing a number.
Return Value
StringToShortArray
The function symbol-wise copies a string into a specified place of an array of ushort type. It returns
the number of copied elements.
int StringToShortArray(
string text_string, // source string
ushort& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);
Parameters
text_string
[in] String to copy
array[]
[out] Array of ushort type (analog of wchar_t type).
start=0
[in] Position, from which copying starts. Default - 0.
count=-1
[in] Number of array elements to copy. Defines length of a resulting string. Default value is -1,
which means copying up to the array end, or till terminal 0.Terminal 0 will also be copied to the
recipient array, in this case the size of a dynamic array can be increased if necessary to the size
of the string. If the size of the dynamic array exceeds the length of the line, the size of the array
will not be reduced.
Return Value
StringToTime
The function converts a string containing time or date in "yyyy.mm.dd [hh:mi]" format into datetime
type.
datetime StringToTime(
string value // date string
);
Parameters
value
[in] String in " yyyy.mm.dd hh:mi " format.
Return Value
Value of datetime type containing total number of seconds that elapsed since 01.01.1970.
StringFormat
The function formats obtained parameters and returns a string.
string StringFormat(
string format, // string with format description
... ... // parameters
);
Parameters
format
[in] String containing method of formatting. Formatting rules are the same as for the
PrintFormat function.
...
[in] Parameters, separated by a comma.
Return Value
String.
See also
PrintFormat, DoubleToString,ColorToString, TimeToString
Mathematical Functions
A set of mathematical and trigonometric functions.
Function Action
MathAbs
The function returns the absolute value (modulus) of the specified numeric value.
double MathAbs(
double value // numeric value
);
Parameters
value
[in] Numeric value.
Return Value
Note
MathArccos
The function returns the arccosine of x within the range 0 to in radians.
double MathArccos(
double val // -1<val<1
);
Parameters
val
[in] The val value between -1 and 1, the arc cosine of which is to be calculated.
Return Value
Arc cosine of a number in radians. If val is less than -1 or more than 1, the function returns NaN
(indeterminate value).
Note
See also
Real types (double, float)
MathArcsin
The function the arc sine of x within the range of - /2 to /2 radians.
double MathArcsin(
double val // -1<value<1
);
Parameters
val
[in] The val value between -1 and 1, the arc sine of which is to be calculated.
Return Value
Arc sine of the val number in radians within the range of - /2 to /2 radians. If val is less than -1
or more than 1, the function returns NaN (indeterminate value).
Note
See also
Real types (double, float)
MathArctan
The function returns the arc tangent of x. If x is equal to 0, the function returns 0.
double MathArctan(
double value // tangent
);
Parameters
value
[in] A number representing a tangent.
Return Value
Note
MathCeil
The function returns integer numeric value closest from above.
double MathCeil(
double val // number
);
Parameters
val
[in] Numeric value.
Return Value
Numeric value representing the smallest integer that exceeds or equals to val.
Note
MathCos
The function returns the cosine of an angle.
double MathCos(
double value // number
);
Parameters
value
[in] Angle in radians.
Return Value
Note
MathExp
The function returns the value of e raised to the power of d.
double MathExp(
double value // power for the number e
);
Parameters
value
[in] A number specifying the power.
Return Value
A number of double type. At overflow, the function returns INF (infinity), in case of order loss
MathExp returns 0.
Note
See also
Real types (double, float)
MathFloor
The function returns integer numeric value closest from below.
double MathFloor(
double val // number
);
Parameters
val
[in] Numeric value.
Return Value
A numeric value representing the largest integer that is less than or equal to val.
Note
MathLog
The function returns a natural logarithm.
double MathLog(
double val // value to take the logarithm
);
Parameters
val
[in] Value logarithm of which is to be found.
Return Value
The natural logarithm of val in case of success. If val is negative, the function returns NaN
(undetermined value). If val is equal to 0, the function returns INF (infinity).
Note
See also
Real types (double, float)
MathLog
Returns the logarithm of a number by base 10.
double MathLog10(
double val // number to take logarithm
);
Parameters
val
[in] Numeric value the common logarithm of which is to be calculated.
Return Value
The common logarithm in case of success. If val is negative, the function returns NaN
(undetermined value). If val is equal to 0, the function returns INF (infinity).
Note
See also
Real types (double, float)
MathMax
The function returns the maximal value of two values.
double MathMax(
double value1, // first value
double value2 // second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
Note
Instead of MathMax() you can use fmax(). Functions fmax(), fmin(), MathMax(), MathMin() can
work with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the minor type is
automatically cast to the major type. The type of the return value corresponds to the major type.
MathMin
The function returns the minimal value of two values.
double MathMin(
double value1, // first value
double value2 // second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
Note
Instead of MathMin() you can use fmin(). Functions fmax(), fmin(), MathMax(), MathMin() can work
with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the minor type is
automatically cast to the major type. The type of the return value corresponds to the major type.
MathMod
The function returns the real remainder of division of two numbers.
double MathMod(
double value, // divident value
double value2 // divisor value
);
Parameters
value
[in] Dividend value.
value2
[in] Divisor value.
Return Value
The MathMod function calsulates the real value of f of val / y such that val = i * y + f , where i is an
integer, f has the same sign as val, and the absolute value of f is less than the absolute value of y.
Note
MathPow
The function raises a base to a specified power.
double MathPow(
double base, // base
double exponent // exponent value
);
Parameters
base
[in] Base.
exponent
[in] Exponent value.
Return Value
Note
MathRand
Returns a pseudorandom integer within the range of 0 to 32767.
int MathRand();
Return Value
Note
Before the first call of the function, it's necessary to call MathSrand to set the generator of
pseudorandom numbers to the initial state.
Note
MathRound
The function returns a value rounded off to the nearest integer of the specified numeric value.
double MathRound(
double value // value to be rounded
);
Parameters
value
[in] Numeric value before rounding.
Return Value
Note
MathSin
Returns the sine of a specified angle.
double MathSin(
double value // argument in radians
);
Parameters
value
[in] Angle in radians.
Return Value
Note
MathSqrt
Returns the square root of a number.
double MathSqrt(
double value // positive number
);
Parameters
value
[in] Positive numeric value.
Return Value
Square root of value. Of value is negative, MathSqrt returns NaN (indeterminate value).
Note
See also
Real types (double, float)
MathSrand
Sets the starting point for generating a series of pseudorandom integers.
void MathSrand(
int seed // initializing number
);
Parameters
seed
[in] Starting number for the row of random numbers.
Return Value
No return value.
Note
To re-initialize the generator (i.e. set generator into previous initial state), it's necessary to use
value 1 as the initializing parameter. Any other value for the initial number sets the generator to
the random starting point.
MathRand returns pseudorandom numbers that are generated in succession. Calling MathRand
before any call to MathSrand generates the same sequence as calling MathSrand with parameter 1.
MathTan
The function returns a tangent of a number.
double MathTan(
double rad // argument in radians
);
Parameters
rad
[in] Angle in radians.
Return Value
Tangent of rad. If rad is greater than or equal to 263, or less than or equal to -263, a loss of
significance in the result occurs, in which case the function returns an indefinite.
Note
See also
Real types (double, float)
MathIsValidNumber
It checks the correctness of a real number.
bool MathIsValidNumber(
double number // number to check
);
Parameters
number
[in] Checked numeric value.
Return Value
It returns true, if the checked value is an acceptable real number. If the checked value is a plus or
minus infinity, or "not a number" (NaN), the function returns false.
Example:
double abnormal=MathArcsin(2.0);
if(!MathIsValidNumber(abnormal)) Print("Attention! MathArcsin(2.0) = ",abnormal);
See also
Real types (double, float)
String Functions
This is a group of functions intended for working with data of the string type.
Function Action
StringAdd
The function adds a substring to the end of a string.
bool StringAdd(
string& string_var, // string, to which we add
string add_substring // string, which is added
);
Parameters
string_var
[in][out] String, to which another one is added.
add_substring
[in] String that is added ti the end of a source string.
Return Value
In case of success returns true, otherwise false. In order to get an error code, the GetLastError()
function should be called.
Note
The StringAdd() add functions is faster and memory saving, as compared to binding strings using
addition operations.
Example:
void OnStart()
{
string a="a",b="b",c;
//--- first method
int start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c = a + b' = ",(stop-start)," milliseconds, i = ",i);
start=GetTickCount();
a="a"; // re-initialize variable a
for(i=0;i<length;i++)
{
int k=StringConcatenate(c,a,b);
}
stop=GetTickCount();
Print("time for 'StringConcatenate(c,a,b)' = ",(stop-start)," milliseconds, i = ",i);
}
See also
StringConcatenate
StringBufferLen
The function returns the size of buffer distributed for the string.
int StringBufferLen(
string string_var // string
)
Parameters
string_var
[in] String.
Return Value
The value 0 means that the string is constant and buffer size can't be changed. -1 means that the
string belongs to the client terminal, and modification of the buffer contents can have
indeterminate results.
Note
Example:
void OnStart()
{
long length=1000;
string a="a",b="b";
//---
long i;
Print("before: StringBufferLen(a) = ",StringBufferLen(a),
" StringLen(a) = ",StringLen(a));
for(i=0;i<length;i++)
{
StringAdd(a,b);
}
Print("after: StringBufferLen(a) = ",StringBufferLen(a),
" StringLen(a) = ",StringLen(a));
}
See also
StringAdd, StringInit, StringLen, StringFill
StringCompare
The function compares two strings and returns the comparison result in form of an integer.
int StringCompare(
const string& string1, // the first string in the comparison
const string& string2, // the second string in the comparison
bool case_sensitive=true // case sensitivity mode selection for the comparison
);
Parameters
string1
[in] The first string.
string2
[in] The second string.
case_sensitive=true
[in] Case sensitivity mode selection. If it is true, then "A">"a". If it is false, then "A"="a". By
default the value is equal to true.
Return Value
-1 (minus one), if string1<string2
0 (zero), if string1=string2
1 (one), if string1>string2
Note
The strings are compared symbol by symbol, the symbols are compared in the alphabetic order in
accordance with the current code page.
Example:
void OnStart()
{
//--- what is larger - apple or home?
string s1="Apple";
string s2="home";
See also
String Type, CharToString(), ShortToString(), StringToCharArray(), StringToShortArray(),
StringGetCharacter(), Use of a Codepage
StringConcatenate
The function forms a string of passed parameters and returns the size of the formed string.
Parameters can be of any type. Number of parameters can't be less than 2 or more than 64.
int StringConcatenate(
string& string_var, // string to form
void argument1 // first parameter of any simple type
void argument2 // second parameter of any simple type
... // next parameter of any simple type
);
Parameters
string_var
[in][out] String that will be formed as a result of concatenation.
argumentN
[in] Any comma separated values. From 2 to 63 parameters of any simple type.
Return Value
Returns the string length, formed by concatenation of parameters transformed into string type.
Parameters are transformed into strings according to the sane rules as in Print() and Comment().
Note
StringConcatenate() is faster and memory saving, as compared to binding strings using addition
operations, because they don't use temporary variables of string type.
See also
StringAdd
StringFill
It fills out a selected string by specified symbols.
bool StringFill(
string& string_var, // string to fill
ushort character // symbol that will fill the string
);
Parameters
string_var
[in][out] String, that will be filled out by the selected symbol.
character
[in] Symbol, by which the string will be filled out.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
Note
Filling out a string at place means that symbols are inserted directly to the string without
transitional operations of new string creation or copying. This allows to save the operation time.
Example:
void OnStart()
{
string str;
StringInit(str,20,'_');
Print("str = ",str);
StringFill(str,0);
Print("str = ",str,": StringBufferLen(str) = ", StringBufferLen(str));
}
// Result
// str = ____________________
// str = : StringBufferLen(str) = 20
//
See also
StringBufferLen, StringLen, StringInit
StringFind
Search for a substring in a string.
int StringFind(
string string_value, // string in which search is made
string match_substring, // what is searched
int start_pos=0 // from what position search starts
);
Parameters
string_value
[in] String, in which search is made.
match_substring
[in] Searched substring.
start_pos=0
[in] Position in the string from which search is started.
Return Value
Returns position number in a string, from which the searched substring starts, or -1, if the
substring is not found.
StringGetCharacter
Returns value of a symbol, located in the specified position of a string.
ushort StringGetCharacter(
string string_value, // string
int pos // symbol position in the string
);
Parameters
string_value
[in] String.
pos
[in] Position of a symbol in the string. Can be from 0 to StringLen(text) -1.
Return Value
Symbol code or 0 in case of an error. To get the error code call GetLastError().
StringInit
Initializes a string by specified symbols and provides the specified string size.
bool StringInit(
string& string_var, // string to initialize
int new_len=0, // required string length after initialization
ushort character=0 // symbol, by which the string will be filled
);
Parameters
string_var
[in][out] String that should be initialized and deinitialized.
new_len=0
[in] String length after initialization. If length=0, it deinitializes the string, i.e. the string buffer
is cleared and the buffer address is zeroed.
character=0
[in] Symbol to fill the string.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
Note
If character=0 and the length new_len>0, the buffer of the string of indicated length will be
distributed and filled by zeroes. The string length will be equal to zero, because the whole buffer is
filled out by string terminators.
Example:
void OnStart()
{
//---
string str;
StringInit(str,200,0);
Print("str = ",str,": StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
}
/* Result
str = : StringBufferLen(str) = 200 StringLen(str) = 0
*/
See also
StringBufferLen, StringLen
StringLen
Returns the number of symbols in a string.
int StringLen(
string string_value // string
);
Parameters
string_value
[in] String to calculate length.
Return Value
StringReplace
It replaces all the found substrings of a string by a set sequence of symbols.
int StringReplace(
string& str, // the string in which substrings will be replaced
const string find, // the searched substring
const string replacement // the substring that will be inserted to the found positions
);
Parameters
str
[in][out] The string in which you are going to replace substrings.
find
[in] The desired substring to replace.
replacement
[in] The string that will be inserted instead of the found one.
Return Value
The function returns the number of replacements in case of success, otherwise -1. To get an error
code call the GetLastError() function.
Note
If the function has run successfully but no replacements have been made (the substring to replace
was not found), it returns 0.
The error can result from incorrect str or find parameters (empty or non-initialized string, see
StringInit() ). Besides, the error occurs if there is not enough memory to complete the replacement.
Example:
string text="The quick brown fox jumped over the lazy dog.";
int replaced=StringReplace(text,"quick","slow");
replaced+=StringReplace(text,"brown","black");
replaced+=StringReplace(text,"fox","bear");
Print("Replaced: ", replaced,". Result=",text);
// Result
// Replaced: 3. Result=The slow black bear jumped over the lazy dog.
//
See also
StringSetCharacter(), StringSubstr()
StringSetCharacter
Returns copy of a string with a changed character in a specified position.
bool StringSetCharacter(
string& string_var, // string
int pos, // position
ushort character // character
);
Parameters
string_var
[in][out] String.
pos
[in] Position of a character in a string. Can be from 0 to StringLen(text).
character
[in] Symbol code Unicode.
Note
If pos is less than string length and the symbol code value = 0, the string is cut off (but the buffer
size, distributed for the stringremains unchanged). The string length becomes equal to pos.
If pos is equal to string length, the specified symbol is added at the string end, and the length is
enlarged by one.
Example:
void OnStart()
{
string str="0123456789";
Print("before: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
//--- add zero value in the middle
StringSetCharacter(str,6,0);
Print(" after: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
//--- add symbol at the end
int size=StringLen(str);
StringSetCharacter(str,size,'+');
Print("addition: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
}
/* Result
before: str = 0123456789 ,StringBufferLen(str) = 0 StringLen(str) = 10
after: str = 012345 ,StringBufferLen(str) = 16 StringLen(str) = 6
addition: str = 012345+ ,StringBufferLen(str) = 16 StringLen(str) = 7
*/
See also
StringSubstr
Extracts a substring from a text string starting from the specified position.
string StringSubstr(
string string_value, // string
int start_pos, // position to start with
int length=-1 // length of extracted string
);
Parameters
string_value
[in] String to extract a substring from.
start_pos
[in] Initial position of a substring. Can be from 0 to StringLen(text) -1.
length=-1
[in] Length of an extracted substring. If the parameter value is equal to -1 or parameter isn't set,
the substring will be extracted from the indicated position till the string end.
Return Value
StringToLower
Transforms all all symbols of a selected string into lowercase by location.
bool StringToLower(
string& string_var // string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
StringToUpper
Transforms all all symbols of a selected string into capitals by location.
bool StringToUpper(
string& string_var // string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
StringTrimLeft
The function cuts line feed characters, spaces and tabs in the left part of the string till the first
meaningful symbol. The string is modified at place.
int StringTrimLeft(
string& string_var // string to cut
);
Parameters
string_var
[in][out] String that will be cut from the left.
Return Value
StringTrimRight
The function cuts line feed characters, spaces and tabs in the right part of the string after the last
meaningful symbol. The string is modified at place.
int StringTrimRight(
string& string_var // string to cut
);
);
Parameters
string_var
[in][out] String that will be cut from the right.
Return Value
Function Action
TimeCurrent
Returns the last known server time server, time of the last quote receipt for one of the symbols
selected in the "Market Watch" window. In the OnTick() handler, this function returns the time of the
received handled tick. In other cases (for example, call in handlers OnInit(), OnDeinit(), OnTimer()
and so on) this is the time of the last quote receipt for any symbol available in the "Market Watch"
window, the time shown in the title of this window. The time value is formed on a trade server and
does not depend on the time settings on your computer. There are 2 variants of the function.
datetime TimeCurrent();
datetime TimeCurrent(
MqlDateTime& dt_struct // structure type variable
);
Parameters
dt_struct
[out] MqlDateTime structure type variable.
Return Value
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
TimeTradeServer
Returns the calculated current time of the trade server. Unlike TimeCurrent(), the calculation of the
time value is performed in the client terminal and depends on the time settings on your computer.
There are 2 variants of the function.
datetime TimeTradeServer();
datetime TimeTradeServer(
MqlDateTime& dt_struct // Variable of structure type
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
TimeLocal
Returns the local time of a computer, where the client terminal is running. There are 2 variants of the
function.
datetime TimeLocal();
datetime TimeLocal(
MqlDateTime& dt_struct // Variable of structure type
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
TimeGMT
Returns the GMT, which is calculated taking into account the DST switch by the local time on the
computer where the client terminal is running. There are 2 variants of the function.
datetime TimeGMT();
datetime TimeGMT(
MqlDateTime& dt_struct // Variable of structure type
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
TimeDaylightSavings
Returns correction for daylight saving time in seconds, switch to summer time has been made. It
depends on the time settings of your computer.
int TimeDaylightSavings();
Return Value
TimeGMTOffset
Returns the current difference between GMT time and the local computer time in seconds, taking into
account switch to winter or summer time. Depends on the time settings of your computer.
int TimeGMTOffset();
Return Value
The value of int type, representing the current difference between the local time of the computer
and GMT time in seconds.
TimeToStruct
Converts a value of datetime type (number of seconds since 01.01.1970) into a structure variable
MqlDateTime.
void TimeToStruct(
datetime dt, // date and time
MqlDateTime& dt_struct // structure for the adoption of values
);
Parameters
dt
[in] Date value to convert.
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
No return value.
StructToTime
Converts a structure variable MqlDateTime into a value of datetime type and returns the resulting
value.
datetime StructToTime(
MqlDateTime$ dt_struct // structure of the date and time
);
Parameters
dt_struct
[in] Variable of structure type MqlDateTime.
Return Value
The value of datetime type containing the number of seconds since 01.01.1970.
Account Information
Functions that return parameters of the current account.
Function Action
AccountInfoDouble
Returns the value of the corresponding account property.
double AccountInfoDouble(
int property_id // identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_DOUBLE.
Return Value
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoDouble()
printf("ACCOUNT_BALANCE = %G",AccountInfoDouble(ACCOUNT_BALANCE));
printf("ACCOUNT_CREDIT = %G",AccountInfoDouble(ACCOUNT_CREDIT));
printf("ACCOUNT_PROFIT = %G",AccountInfoDouble(ACCOUNT_PROFIT));
printf("ACCOUNT_EQUITY = %G",AccountInfoDouble(ACCOUNT_EQUITY));
printf("ACCOUNT_MARGIN = %G",AccountInfoDouble(ACCOUNT_MARGIN));
printf("ACCOUNT_FREEMARGIN = %G",AccountInfoDouble(ACCOUNT_FREEMARGIN));
printf("ACCOUNT_MARGIN_LEVEL = %G",AccountInfoDouble(ACCOUNT_MARGIN_LEVEL));
printf("ACCOUNT_MARGIN_SO_CALL = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL));
printf("ACCOUNT_MARGIN_SO_SO = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_SO));
}
See also
SymbolInfoDouble, SymbolInfoString, SymbolInfoInteger, PrintFormat
AccountInfoInteger
Returns the value of the properties of the account.
long AccountInfoInteger(
int property_id // Identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_INTEGER.
Return Value
Note
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoInteger()
printf("ACCOUNT_LOGIN = %d",AccountInfoInteger(ACCOUNT_LOGIN));
printf("ACCOUNT_LEVERAGE = %d",AccountInfoInteger(ACCOUNT_LEVERAGE));
bool thisAccountTradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_ALLOWED);
bool EATradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_EXPERT);
ENUM_ACCOUNT_TRADE_MODE tradeMode=AccountInfoInteger(ACCOUNT_TRADE_MODE);
ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE);
case(ACCOUNT_TRADE_MODE_CONTEST):
Print("This is a competition account");
break;
default:Print("This is a real account!");
}
See also
Account Information
AccountInfoString
Returns the value of the corresponding account property.
string AccountInfoString(
int property_id // Identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_STRING.
Return Value
Example:
void OnStart()
{
//--- Show all the information available from the function AccountInfoString()
Print("The name of the broker = ",AccountInfoString(ACCOUNT_COMPANY));
Print("Deposit currency = ",AccountInfoString(ACCOUNT_CURRENCY));
Print("Client name = ",AccountInfoString(ACCOUNT_NAME));
Print("The name of the trade server = ",AccountInfoString(ACCOUNT_SERVER));
}
See also
Account Information
State Checking
Functions that return parameters of the current state of the client terminal
Function Action
GetLastError
Returns the contents of the system variable _LastError.
int GetLastError();
Return Value
Returns the value of the last error that occurred during the execution of an mql5 program.
Note
After the function call, the contents of _LastError are not reset. To reset this variable, you need to
call ResetLastError().
IsStopped
Checks the forced shutdown of an mql5 program.
bool IsStopped();
Return Value
Returns true, if the _StopFlag system variable contains a value other than 0. A nonzero value is
written into _StopFlag, if a mql5 program has been commanded to complete its operation. In this
case, you must immediately terminate the program, otherwise the program will be completed
forcibly from the outside after 3 seconds.
UninitializeReason
Returns the code of a reason for deinitialization.
int UninitializeReason();
Return Value
Returns the value of _UninitReason which is formed before OnDeinit() is called. Value depends on
the reasons that led to deinitialization.
TerminalInfoInteger
Returns the value of a corresponding property of the mql5 program environment.
int TerminalInfoInteger(
int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one one of the values of the enumeration
ENUM_TERMINAL_INFO_INTEGER.
Return Value
TerminalInfoString
the function returns the value of a corresponding property of the mql5 program environment. The
property must be of string type.
string TerminalInfoString(
int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Perhaps one of the values of the enumeration
ENUM_TERMINAL_INFO_STRING.
Return Value
MQL5InfoInteger
Returns the value of a corresponding property of a running mql5 program.
int MQL5InfoInteger(
int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Cam be one of values of the ENUM_MQL5_INFO_INTEGER
enumeration.
Return Value
MQL5InfoString
Returns the value of a corresponding property of a running mql5 program.
string MQL5InfoString(
int property_id // Identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the ENUM_MQL5_INFO_STRING enumeration.
Return Value
Symbol
Returns the name of a symbol of the current chart.
string Symbol();
Return Value
Value of the _Symbol system variable, which stores the name of the current chart symbol.
Period
Returns the current chart timeframe.
ENUM_TIMEFRAMES Period();
Return Value
The contents of the _Period variable that contains the value of the current chart timeframe. The
value can be one of the values of the ENUM_TIMEFRAMES enumeration.
See also
Digits
Returns the number of decimal digits determining the accuracy of price of the current chart symbol.
int Digits();
Return Value
The value of the _Digits variable which stores the number of decimal digits determining the
accuracy of price of the current chart symbol.
Point
Returns the point size of the current symbol in the quote currency.
double Point();
Return Value
The value of the _Point variable which stores the point size of the current symbol in the quote
currency.
Function Action
SymbolsTotal
Returns the number of available (selected in Market Watch or all) symbols.
int SymbolsTotal(
bool selected // True - only symbols in MarketWatch
);
Parameters
selected
[in] Request mode. Can be true or false.
Return Value
If the 'selected' parameter is true, the function returns the number of symbols selected in
MarketWatch. If the value is false, it returns the total number of all symbols.
SymbolName
Returns the name of a symbol.
string SymbolName(
int pos, // number in the list
bool selected // true - only symbols in MarketWatch
);
Parameters
pos
[in] Order number of a symbol.
selected
[in] Request mode. If the value is true, the symbol is taken from the list of symbols selected in
MarketWatch. If the value is false, the symbol is taken from the general list.
Return Value
SymbolSelect
Selects a symbol in the Market Watch window or removes a symbol from the window.
bool SymbolSelect(
string name, // symbol name
bool select // add or remove
);
Parameters
name
[in] Symbol name.
select
[in] Switch. If the value is false, a symbol should be removed from MarketWatch, otherwise a
symbol should be selected in this window. A symbol can't be removed if the symbol chart is open,
or there are open positions for this symbol.
Return Value
SymbolIsSynchronized
The function checks whether data of a selected symbol in the terminal are synchronized with data on
the trade server.
bool SymbolIsSynchronized(
string name, // symbol name
);
Parameters
name
[in] Symbol name.
Return value
See also
SymbolInfoInteger, Organizing Data Access
SymbolInfoDouble
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
double SymbolInfoDouble(
string name, // symbol
int prop_id // identifier of the property
);
2. Returns true or false depending on whether a function is successfully performed. In case of success,
the value of the property is placed into a recipient variable, passed by reference by the last
parameter.
bool SymbolInfoDouble(
string name, // symbol
int prop_id, // identifier of the property
double& double_var // here we assume the property value
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_DOUBLE enumeration.
double_var
[out] Variable of double type receiving the value of the requested property.
Return Value
Example:
void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}
SymbolInfoInteger
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
long SymbolInfoInteger(
string name, // symbol
int prop_id // identifier of a property
);
2. Returns true or false depending on whether a function is successfully performed. In case of success,
the value of the property is placed into a recipient variable, passed by reference by the last
parameter.
bool SymbolInfoInteger(
string name, // symbol
int prop_id, // identifier of a property
long& long_var // here we assume the property value
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_INTEGER enumeration.
long_var
[out] Variable of the long type receiving the value of the requested property.
Return Value
Example:
void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
SymbolInfoString
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
string SymbolInfoString(
string name, // Symbol
int prop_id // Identifier properties
);
2. Returns true or false, depending on the success of a function. If successful, the value of the
property is placed in a foster variables passed by reference the last parameter.
bool SymbolInfoString(
string name, // Symbol
int prop_id, // Identifier properties
string& string_var // Here we assume the property value
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_STRING enumeration.
string_var
[out] Variable of the string type receiving the value of the requested property.
Return Value
SymbolInfoTick
The function returns current prices of a specified symbol in a variable of the MqlTick type.
bool SymbolInfoTick(
string symbol, // symbol name
MqlTick& tick // reference to a structure
);
Parameters
symbol
[in] Symbol name.
book[]
[out] Link to the structure of the MqlTick type, to which the current prices and time of the last
price update will be placed.
Return Value
SymbolInfoSessionQuote
Allows receiving time of beginning and end of the specified quoting sessions for a specified symbol
and weekday..
bool SymbolInfoSessionQuote(
string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // time of the session beginning
datetime& to // time of the session end
);
Parameters
name
[in] Symbol name.
ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of
sessions starts with 0.
from
[out] Session beginning time in seconds from 00 hours 00 minutes, in the returned value date
should be ignored.
to
[out] Session end time in seconds from 00 hours 00 minutes, in the returned value date should be
ignored.
Return Value
If data for the specified session, symbol and day of the week are received, returns true, otherwise
returns false.
See also
Symbol Properties, TimeToStruct, Data Structures
SymbolInfoSessionTrade
Allows receiving time of beginning and end of the specified trading sessions for a specified symbol
and weekday..
bool SymbolInfoSessionTrade(
string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // session beginning time
datetime& to // session end time
);
Parameters
name
[in] Symbol name.
ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of
sessions starts with 0.
from
[out] Session beginning time in seconds from 00 hours 00 minutes, in the returned value date
should be ignored.
to
[out] Session end time in seconds from 00 hours 00 minutes, in the returned value date should be
ignored.
Return value
If data for the specified session, symbol and day of the week are received, returns true, otherwise
returns false.
See also
Symbol Properties, TimeToStruct, Data Structures
MarketBookAdd
Provides opening of Depth of Market for a selected symbol, and subscribes for receiving notifications
of the DOM changes.
bool MarketBookAdd(
string symbol // symbol
);
Parameters
symbol
[in] The name of a symbol, whose Depth of Market is to be used in the Expert Advisor or script.
Return Value
Note
Normally, this function must be called from the OnInit() function or in the class constructor. To
handle incoming alerts, in the Expert Advisor program must contain the function void OnBookEvent
(string& symbol).
See also
Structure of Depth of Market, Structures and Classes
MarketBookRelease
Provides closing of Depth of Market for a selected symbol, and cancels the subscription for receiving
notifications of the DOM changes.
bool MarketBookRelease(
string symbol // symbol
);
Parameters
symbol
[in] Symbol name.
Return Value
Note
Normally, this function must be called from the OnDeinit() function, if the corresponding
MarketBookAdd() function has been called in the OnInit() function. Or it must be called from the
class destructor, if the corresponding MarketBookAdd() function has been called from the class
constructor.
See also
Structure of Depth of Market, Structures and Classes
MarketBookGet
Returns a structure array MqlBookInfo containing records of the Depth of Market of a specified
symbol.
bool MarketBookGet(
string symbol, // symbol
MqlBookInfo& book[] // reference to an array
);
Parameters
symbol
[in] Symbol name.
book[]
[in] Reference to an array of Depth of Market records. The array can be pre-allocated for a
sufficient number of records. If a dynamic array hasn't been pre-allocated in the operating
memory, the client terminal will distribute the array itself.
Return Value
Note
Example:
MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo for ",Symbol());
for(int i=0;i<size;i++)
{
Print(i+":",priceArray[i].price
+" Volume = "+priceArray[i].volume,
" type = ",priceArray[i].type);
}
}
else
{
Print("Could not get contents of the symbol DOM ",Symbol());
}
See also
Structure of Depth of Market, Structures and Classes
There is an important exception to this rule: if timeseries and indicator values need to be copied
often, for example at each call of OnTick() in Expert Advisors or at each call of OnCalculate() in
indicators, in this case one should better use statically distributed arrays, because operations of
memory allocation for dynamic arrays require additional time, and this will have effect during
testing and optimization.
When using functions accessing timeseries and indicator values, indexing direction should be taken
into account. This is described in section Indexing direction in arrays and timeseries.
Access to indicator and timeseries data is implemented irrespective of the fact whether the requested
data are ready (the so called asynchronous access). This is critically important for the calculation of
custom indicator, so if there are no data, functions of Copy...() type immediately return an error.
However, when accessing form Expert Advisors and scripts, several attempts to receive data are
made in a small pause, which is aimed at providing some time necessary to download required
timeseries of to calculate indicator values.
The Organizing Data Access section describes details of receiving, storing and requesting price data in
the MetaTrader 5 client terminal.
It is historically accepted that an access to the price data in an array is performed from the end of the
data. Physically, the new data are always written at the array end, but the index of the array is always
equal to zero. The 0 index in the timeseries array denotes data of the current bar, i.e. the bar that
corresponds to the unfinished time interval in this timeframe.
A timeframe is the time period, during which a single price bar is formed. There are 21 predefined
standard timeframes.
Function Action
Despite the fact that by using the ArraySetAsSeries() function it is possible to set up in arrays access
to elements like that in timeseries, it should be remembered that the array elements are physically
stored in one and the same order - only indexing direction changes. To demonstrate this fact let's
perform an example:
datetime TimeAsSeries[];
//--- set access to the array like to a timeseries
ArraySetAsSeries(TimeAsSeries,true);
ResetLastError();
int copied=CopyTime(NULL,0,0,10,TimeAsSeries);
if(copied<=0)
{
Print("The copy operation of the open time values for last 10 bars has failed");
return;
}
Print("TimeCurrent =",TimeCurrent());
Print("ArraySize(Time) =",ArraySize(TimeAsSeries));
int size=ArraySize(TimeAsSeries);
for(int i=0;i<size;i++)
{
Print("TimeAsSeries["+i+"] =",TimeAsSeries[i]);
}
datetime ArrayNotSeries[];
ArraySetAsSeries(ArrayNotSeries,false);
ResetLastError();
copied=CopyTime(NULL,0,0,10,ArrayNotSeries);
if(copied<=0)
{
Print("The copy operation of the open time values for last 10 bars has failed");
return;
}
size=ArraySize(ArrayNotSeries);
for(int i=size-1;i>=0;i--)
{
Print("ArrayNotSeries["+i+"] =",ArrayNotSeries[i]);
}
As we see from the output, as the index of TimeAsSeries array increases, the time value of the index
decreases, i.e. we move from the present to the past. For the common array ArrayNotSeries the result
is different - as index grows, we move from past to present.
See Also
ArrayIsDynamic, ArrayGetAsSeries, ArraySetAsSeries, ArrayIsSeries
An indicator buffer is a dynamic array of type double, whose size is managed by the client terminals,
so that it always corresponds to the number of bars the indicator is calculated on. A usual dynamic
array of type double is assigned as an indicator buffer using the SetIndexBuffer() function. Indicator
buffers do not require setting of their size using function ArrayResize() - this will be done by the
executing system of the terminal.
Timeseries are arrays with reverse indexing, i.e. the first element of a timeseries is in the extreme
right position, and the last element is in the extreme left position. Timeseries being used for storing
history price data and contain the time information, we can say that the newest data are placed in the
extreme right position of the timeseries, while the oldest data are in the extreme left position.
So the timeseries element with index 0 contains the information about the latest quote of a symbol. If
a timeseries contains data on a daily timeframe, data of the current yet uncompleted day are located
on the zero position, and the position with index 1 contains yesterday data.
Function ArraySetAsSeries() allows changing the method of accessing elements of a dynamic array; the
physical order of data storing in the computer memory is not changed at that. This function simply
changes the method of addressing array elements, so when copying one array to another using
function ArrayCopy(), the contents of the recipient array will not depend on the indexing direction in
the source array.
Direction of indexing cannot be changed for statically distributed arrays. Even if an array was passed
as a parameter to a function, attempts to change the indexing direction inside this function will bring
no effect.
For indicator buffers, like for usual arrays, indexing direction can also be set as backward (like in
timeseries), i.e. reference to the zero position in the indicator buffer will mean reference to the last
value on the corresponding indicator buffer and this will correspond to the value of the indicator on
the latest bar. Still, the physical location of indicator bars will be unchanged.
Each custom indicator must necessarily contain the OnCalculate() function, to which price data
required for calculating values in indicator buffers are passed. Indexing direction in these passed
arrays can be found out using function ArrayGetAsSeries().
Arrays passed to the function reflect price data, i.e. these arrays have the sign of a timeseries and
function ArrayIsSeries() will return true when checking these arrays. However, in any case indexing
direction should be checked only by function ArrayGetAsSeries().
In order not to be dependent on default values, ArraySetAsSeries() should be unconditionally called for
the arrays you are going to work with, and set the required direction.
Default indexing direction of all arrays in Expert Advisors, indicators and scripts is left-to-right. If
necessary, in any mql5 program you can request timeseries values on any symbol and timeframe, as
well as values of indicators calculated on any symbol and timeframe.
All these functions work in a similar way. Let's consider the data obtaining mechanism on the example
of CopyBuffer(). It is implied that the indexing direction of requested data is that of timeseries, and
the position with index 0 (zero) stores data of the current yet uncompleted bar. In order to get access
to these data we need to copy the necessary volume of data into the recipient array, e.g. into array
buffer.
When copying we need to specify the starting position in the source array, starting from which data
will be copied to the recipient array. In case of success, the specified number of elements will be
copied to the recipient array from the source array (from the indicator buffer in this case).
Irrespective of the indexing value set in the recipient array, copying is always performed as is shown
in the above figure.
If it is expected that price data will be handled in a loop with a large number of iterations, it is
advisable that you check the fact of forced program termination using the IsStopped() function:
);
if(copied<0) return;
int k=0;
while(k<copied && !IsStopped())
{
//--- Get the value for the k index
double value=Buffer[k];
// ...
// work with value
k++;
}
Example:
See also
Organizing Data Access
Before price data become available in the MetaTrader 5 terminal, they must be received and
processed. To receive data, connection to the MetaTrader 5 trade server must be established. Data
are received in the form of packed blocks of minute bars from the server upon the request of a
terminal.
The mechanism of server reference for data doesn't depend on how the request has been initiated - by
a user when navigating in a chart or in a program way in the MQL5 language.
Data received from a server are automatically unpacked and saved in the HCC intermediate formate.
Data on each symbol are written into a separate folder: terminal_directory\bases\server_name
\history\symbol_name. For example, data on EURUSD received from the MetaQuotes-Demo server will
be stored in terminal_directory\bases\MetaQuotes-Demo\history\EURUSD\.
Data are written into files with .hcc extension. Each file stores data of minute bars for one year. For
example, the file named 2009.hcc in the EURUSD folder contains minute bars of EURUSD for year
2009. These files are used for preparing price data for all timeframes and are not intended for direct
access.
Intermediate HCC files are used as the data source for building price data for requested timeframes in
the HC format. Data of HC format are timeseries that are maximally prepared for a quick access.
They are created upon a request of a chart or a mql5 program. The volume of data should not exceed
the value of the "Max bars in charts" charts. Data are stored for further using in files with hc
extension.
To save resources, data on a timeframe are stored and saved in RAM only if necessary. If not called
long, they are released form RAM and saved into a file. For each timeframe, data are prepared
regardless of whether there are ready data for other timeframes or not. Rules of forming and
accessing data are the same for all timeframes. It means, despite the fact that the unit data stored in
HCC is one minute, the availability of HCC data doesn't mean the availability of data on M1 timeframe
as HC in the same volume.
Receipt of new data from a server calls automatic update of used price data in HC format of all
timeframes. It also leads to the recalculation of all indicators that implicitly use them as input data for
calculations.
The "Max bars in charts" parameter restricts number of bars in HC format available to charts,
indicators and mql5 programs. This is valid for all available timeframes and serves, first of all, to
save computer resources.
When setting a large value of this parameter, it should be remembered, that if deep history price data
for small timeframes are available, memory used for storing timeseries and indicator buffers can
become hundreds of megabytes and reach the RAM restriction for the client terminal program (2Gb for
32-bit applications of MS Windows).
Change of the "Max bars in charts" comes into effect after the client terminal is restarted. Change of
this parameter causes neither automatic referring to a server for additional data, nor forming of
additional bars of timeseries. Additional price data are requested from the server, and timeseries are
updated taking into account the new limitation, in case of either chart scroll to the area with no data,
or when data are requested by a mql5 program.
Volume of data requested from the server corresponds to the required number of bars of this
timeframe with the "Max bars in charts" parameter taken into account. The restriction set by this
parameter is not strict, and in some cases the number of available bars for a timeframe can be a little
more than the current parameter value.
Data Availability
Presence of data on HCC format or even in the prepared for using HC format does not always denote
the absolute availability if these data to be shown in a chart or used in mql5 programs.
When accessing to price data or indicator values from a mql5 program it should be remembered that
their availability in a certain moment of time or starting from a certain moment of time is not
guaranteed. It is connected with the fact that with the purpose of saving resources, the full copy of
data necessary for a mql5 program isn't stored in MetaTrader 5; only direct access to the terminal
data base is given.
The price history for all timeframes is built from common data of HCC format, and any update of data
from a server leads to the update of data for all timeframes and to the recalculation of indicators. Due
to this access to data can be closed, even if these data were available a moment ago.
Since a mql5 program can call data fro any symbol and timeframe, there is a possibility that data of a
necessary timeseries are not formed yet in the terminal or the necessary price data aren't
synchronized with the trade server. In this case it's hard to predict the latency time.
Algorithms using latency cycles are not the best solution. The only exception in this case are scripts,
because they do not have any alternative algorithm choice due to not having event handling. For
custom indicators such algorithms, as well as as any other latency cycles are strongly not
recommended, because they lead to termination of calculation of all indicators and any other handling
of price data of the symbol.
For Expert Advisors and indicators, it is better to use the even model of handling. If during handling
of OnTick() or OnCalculate() event, data receipt for the required timeseries failed, you should exit the
event handler, relying on the access availability during the next call of the handler.
server as packed one minute data, from which any predefined timeseries is constructed then.
Write all actions concerning data receipt as a separate function CheckLoadHistory(symbol, timeframe,
start_date):
The CheckLoadHistory() function is designed as a universal function that can be called from any
program (Expert Advisor, script or indicator); and therefore it requires three input parameters:
symbol name, period and start date to indicate the beginning of price history you need.
Insert necessary checks into the function code before requesting the missing history. First of all, we
should make sure that the symbol name and period value are correct:
Then let's make sure that the symbol is available in the MarketWatch window, i.e., the history for the
symbol will be available when sending a request to a trade server. If there is no such a symbol in
MarketWatch, add it using the SymbolSelect() function.
if(!SymbolInfoInteger(symbol,SYMBOL_SELECT))
{
if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1);
SymbolSelect(symbol,true);
}
Now we should receive the start date of the available history for the indicated symbol/period pair.
Perhaps, the value of the input parameter startdate, passed to CheckLoadHistory(), is within the
available history; then request to a trade server is not needed. In order to obtain the very first date
for the symbol-period as of the moment, the SeriesInfoInteger() function with the SERIES_FIRSTDATE
modifier is used.
SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date);
if(first_date>0 && first_date<=start_date) return(1);
The next important check is checking the type of the program, from which the function is called.
Note, sending request to update the timeseries with the same period as that of the indicator, that
calls the update, is undesirable. The undesirability of requesting data on the same symbol-period as
that of the indicator is conditioned by the fact that update of history data is performed in the same
thread where the indicator operates. So the possibility of clinch occurrence is high. To check this use
the MQL5InfoInteger() function with the MQL5_PROGRAM_TYPE modifier.
If all the checks have been passed successfully, make the last attempt to d without referring to the
trade server. First let's find out the start date, for which minute data in HCC format are available.
Request this value using the SeriesInfoInteger() function with the SERIES_TERMINAL_FIRSTDATE
modifier and again compare it to the value of the start_date parameter.
if(SeriesInfoInteger(symbol,PERIOD_M1,SERIES_TERMINAL_FIRSTDATE,first_date))
{
//--- there is loaded data to build timeseries
if(first_date>0)
{
//--- force timeseries build
CopyTime(symbol,period,first_date+PeriodSeconds(period),1,times);
//--- check date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(2);
}
}
If after all the checks the execution thread is still in the body of the CheckLoadHistory() function, it
means there is a necessity to request the missing price data from a trade server. First, return the
value of "Max bars in chart" using the TerminalInfoInteger() function:
int max_bars=TerminalInfoInteger(TERMINAL_MAXBARS);
We'll need it to prevent requesting extra data. Then find the very first date in the symbol history on
the trade server (regardless of the period) using already known function SeriesInfoInteger() with the
SERIES_SERVER_FIRSTDATE modifier.
datetime first_server_date=0;
while(!SeriesInfoInteger(symbol,PERIOD_M1,SERIES_SERVER_FIRSTDATE,first_server_date) && !IsStopp
Sleep(5);
Since the request is an asynchronous operation, the function is called in the cycle with a small delay of
5 milliseconds until the first_server_date variable receives a value, or the cycle execution is
terminated by a user (IsStopped() will return true in this case). Let's indicate a correct value of the
start date, starting from which we request price data from a trade server.
if(first_server_date>start_date) start_date=first_server_date;
if(first_date>0 && first_date<first_server_date)
Print("Warning: first server date ",first_server_date," for ",
symbol," does not match to first series date ",first_date);
If the start date first_server_date of the server is lower than the start date first_date of the symbol in
HCC format, the corresponding entry will be output in the journal.
Now we are ready to make a request to a trade server asking for missing price data. Make the request
in the form of a cycle and start filling out its body:
while(!IsStopped())
{
//1. wait for synchronization between the re-built timeseries and intermediate history as HHC
//2. receive the current number of bars n this timeseries
// if bars is larger than Max_bars_in_chart, we can exit, work is over
//3. obtain the start date first_date in the re-built timeseries and compare it to start_date
// if first_date is lower than start_date, we can exit, work is over
//4. request from a server a new part of history - 100 bars starting from last available bar
}
while(!IsStopped())
{
//--- 1.wait till timeseries re-build process is over
while(!SeriesInfoInteger(symbol,period,SERIES_SYNCRONIZED) && !IsStopped())
Sleep(5);
//--- 2.request how many bars we have
int bars=Bars(symbol,period);
if(bars>0)
{
//--- bars more than can be drawn in the chart, exit
if(bars>=max_bars) return(-2);
//--- 3. return the current start date in the timeseries
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
// start date was earlier than that requested, task completed
if(first_date>0 && first_date<=start_date) return(0);
}
//4. Request from a server a new part of history - 100 bars starting from last available bar
}
The last fourth point is left - requesting history. We can't refer to a server directly, but any Copy-
function automatically initiates request sending to a server, if the history in HCC format is not
enough. Since the time of the very first start date in the first_date variable is the simple and natural
criterion to evaluate the request execution degree, then the easiest way is to use the CopyTime()
function.
When calling functions that copy any data from timeseries, it should be noted that the start parameter
(number of the bar, starting from which price data should be coped) must always be within the
available terminal history. If you have only 100 bars, it meaningless to try copying 300 bars starting
from the bar with the index 500. Such a request will be understood as an erroneous and won't be
handled, i.e. no additional history will be loaded from a trade server.
That's why we'll copy by 100 bars starting from the bar with the bars index. This will provide the
smooth loading of missing history from a trade server. Actually a little more than the requested 100
bars will be loaded, while server sends oversized history.
int copied=CopyTime(symbol,period,bars,100,times);
After the copying operation, we should analyze the number of copied elements. If the attempt fails,
then value of the copied will be equal to null and the value of the fail_cnt counter will be increased by
1. After 100 failing attempts, the operation of the function will be stopped.
int fail_cnt=0;
...
int copied=CopyTime(symbol,period,bars,100,times);
if(copied>0)
{
//--- check data
if(times[0]<=start_date) return(0); // the copied value is smaller, ready
if(bars+copied>=max_bars) return(-2); // bars are more than can be drawn in the chart, ready
fail_cnt=0;
}
else
{
//--- no more than 100 failing attempts in succession
fail_cnt++;
if(fail_cnt>=100) return(-5);
Sleep(10);
}
So, not only correct handling of the current situation at each moment of execution is implemented in
the function, but also the termination code is returned, that can be handled after calling the
CheckLoadHistory() function for getting additional information. For example, this way:
int res=CheckLoadHistory(InpLoadedSymbol,InpLoadedPeriod,InpStartDate);
switch(res)
{
case -1 : Print("Unknown symbol ",InpLoadedSymbol); break;
case -2 : Print("More requested bars than can be drawn in the chart"); break;
case -3 : Print("Execution stopped by user"); break;
case -4 : Print("Indicator mustn't load its own data"); break;
case -5 : Print("Loading failed"); break;
case 0 : Print("All data loaded"); break;
case 1 : Print("Already available data in timeseries are enough"); break;
case 2 : Print("Timeseries is built from available terminal data"); break;
default : Print("Execution result undefined");
}
The full code of the function can be found in the example of a script that shows the correct
organization of access to any data with the handling of request results.
Code:
//+------------------------------------------------------------------+
//| TestLoadHistory.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.02"
#property script_show_inputs
//--- input parameters
input string InpLoadedSymbol="NZDUSD"; // Symbol to be load
input ENUM_TIMEFRAMES InpLoadedPeriod=PERIOD_H1; // Period to be load
input datetime InpStartDate=D'2006.01.01'; // Start date
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
Print("Start load",InpLoadedSymbol+","+GetPeriodName(InpLoadedPeriod),"from",InpStartDate);
//---
int res=CheckLoadHistory(InpLoadedSymbol,InpLoadedPeriod,InpStartDate);
switch(res)
{
case -1 : Print("Unknown symbol ",InpLoadedSymbol); break;
case -2 : Print("Requested bars more than max bars in chart"); break;
case -3 : Print("Program was stopped"); break;
case -4 : Print("Indicator shouldn't load its own data"); break;
case -5 : Print("Load failed"); break;
case 0 : Print("Loaded OK"); break;
case 1 : Print("Loaded previously"); break;
case 2 : Print("Loaded previously and built"); break;
default : Print("Unknown result");
}
//---
datetime first_date;
SeriesInfoInteger(InpLoadedSymbol,InpLoadedPeriod,SERIES_FIRSTDATE,first_date);
int bars=Bars(InpLoadedSymbol,InpLoadedPeriod);
Print("First date ",first_date," - ",bars," bars");
//---
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int CheckLoadHistory(string symbol,ENUM_TIMEFRAMES period,datetime start_date)
{
datetime first_date=0;
datetime times[100];
//--- check symbol & period
if(symbol==NULL || symbol=="") symbol=Symbol();
if(period==PERIOD_CURRENT) period=Period();
//--- check if symbol is selected in the MarketWatch
if(!SymbolInfoInteger(symbol,SYMBOL_SELECT))
{
if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1);
SymbolSelect(symbol,true);
}
//--- check if data is present
SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date);
if(first_date>0 && first_date<=start_date) return(1);
//--- don't ask for load of its own data if it is an indicator
if(MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR && Period()==period && Symbol()==symbol
return(-4);
//--- second attempt
if(SeriesInfoInteger(symbol,PERIOD_M1,SERIES_TERMINAL_FIRSTDATE,first_date))
{
//--- there is loaded data to build timeseries
if(first_date>0)
{
//--- force timeseries build
CopyTime(symbol,period,first_date+PeriodSeconds(period),1,times);
//--- check date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(2);
}
}
//--- max bars in chart from terminal options
int max_bars=TerminalInfoInteger(TERMINAL_MAXBARS);
//--- load symbol history info
datetime first_server_date=0;
while(!SeriesInfoInteger(symbol,PERIOD_M1,SERIES_SERVER_FIRSTDATE,first_server_date) && !IsStopp
Sleep(5);
//--- fix start date for loading
if(first_server_date>start_date) start_date=first_server_date;
if(first_date>0 && first_date<first_server_date)
Print("Warning: first server date ",first_server_date," for ",symbol,
" does not match to first series date ",first_date);
//--- load data step by step
int fail_cnt=0;
while(!IsStopped())
{
//--- wait for timeseries build
while(!SeriesInfoInteger(symbol,period,SERIES_SYNCRONIZED) && !IsStopped())
Sleep(5);
//--- ask for built bars
int bars=Bars(symbol,period);
if(bars>0)
{
if(bars>=max_bars) return(-2);
//--- ask for first date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(0);
}
//--- copying of next part forces data loading
int copied=CopyTime(symbol,period,bars,100,times);
if(copied>0)
{
//--- check for data
if(times[0]<=start_date) return(0);
if(bars+copied>=max_bars) return(-2);
fail_cnt=0;
}
else
{
//--- no more than 100 failed attempts
fail_cnt++;
if(fail_cnt>=100) return(-5);
Sleep(10);
}
}
//--- stopped
return(-3);
}
//+------------------------------------------------------------------+
//| returns string value of the period |
//+------------------------------------------------------------------+
string GetPeriodName(ENUM_TIMEFRAMES period)
{
if(period==PERIOD_CURRENT) period=Period();
//---
switch(period)
{
case PERIOD_M1: return("M1");
case PERIOD_M2: return("M2");
case PERIOD_M3: return("M3");
case PERIOD_M4: return("M4");
case PERIOD_M5: return("M5");
case PERIOD_M6: return("M6");
case PERIOD_M10: return("M10");
case PERIOD_M12: return("M12");
case PERIOD_M15: return("M15");
case PERIOD_M20: return("M20");
case PERIOD_M30: return("M30");
case PERIOD_H1: return("H1");
case PERIOD_H2: return("H2");
case PERIOD_H3: return("H3");
case PERIOD_H4: return("H4");
case PERIOD_H6: return("H6");
case PERIOD_H8: return("H8");
case PERIOD_H12: return("H12");
case PERIOD_D1: return("Daily");
case PERIOD_W1: return("Weekly");
case PERIOD_MN1: return("Monthly");
}
//---
return("unknown period");
}
SeriesInfoInteger
Returns information about the state of historical data. There are 2 variants of function calls.
long SeriesInfoInteger(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id, // property identifier
);
bool SeriesInfoInteger(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id, // property ID
long& long_var // variable for getting info
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
prop_id
[in] Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER enumeration.
long_var
[out] Variable to which the value of the requested property is placed.
Return Value
For the second case, it returns true, if the specified property is available and it's value has been
placed into long_var variable, otherwise it returns false. For more details about an error, call
GetLastError().
Example:
void OnStart()
{
//---
Print("Total number of bars for the symbol-period at this moment = ",
SeriesInfoInteger(Symbol(),0,SERIES_BARS_COUNT));
Print("The first date in the history for the symbol-period on the server = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE));
Bars
Returns the number of bars count in the history for a specified symbol and period. There are 2
variants of functions calls.
int Bars(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe // period
);
int Bars(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time // end date and time
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_time
[in] Bar time corresponding to the first element.
stop_time
[in] Bar time corresponding to the last element.
Return Value
If the start_time and stop_time parameters are defined, the function returns the number of bars in
the specified time interval, otherwise it returns the total number of bars.
Note
If data for the timeseries with specified parameters are not formed in the terminal by the time of
the Bars() function call, or data of the timeseries are not synchronized with a trade server by the
moment of the function call, the function returns a zero value.
Sample:
int bars=Bars(_Symbol,_Period);
if(bars>0)
{
Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars);
}
else //no available bars
{
//--- data on the symbol might be not synchronized with data on the server
bool synchronized=false;
//--- loop counter
int attempts=0;
// make 5 attempts to wait for synchronization
while(attempts<5)
{
if(SeriesInfoInteger(Symbol(),0,SERIES_SYNCRONIZED))
{
//--- synchronization done, exit
synchronized=true;
break;
}
//--- increase the counter
attempts++;
//--- wait 10 milliseconds till the nest iteration
Sleep(10);
}
//--- exit the loop after synchronization
if(synchronized)
{
Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars
Print("The first date in the terminal history for the symbol-period at the moment = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_FIRSTDATE));
Print("The first date in the history for the symbol on the server = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE));
}
//--- synchronization of data didn't happen
else
{
Print("Failed to get number of bars for ",_Symbol);
}
}
See also
Event Processing Functions
BarsCalculated
Returns the number of calculated data for the specified indicator.
int BarsCalculated(
int indicator_handle, // indicator handle
);
Parameters
indicator_handle
[in] The indicator handle, returned by the corresponding indicator function.
Return Value
Returns the amount of calculated data in the indicator buffer or -1 in the case of error (data not
calculated yet)
Note
The function is useful when it's necessary to get the indicator data immediately after its creation
(indicator handle is available).
Example:
void OnStart()
{
double Ups[];
//--- set timeseries ordering for the the arrays
ArraySetAsSeries(Ups,true);
//--- create handle for the Fractal Indicator
int FractalsHandle=iFractals(NULL,0);
//--- reset the error code
ResetLastError();
//--- try to copy the indicator values
int i,copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Sleep(50);
for(i=0;i<100;i++)
{
if(BarsCalculated(FractalsHandle)>0)
break;
Sleep(50);
}
copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Print("Failed to copy upper fractals. Error = ",GetLastError(),
"i = ",i," copied = ",copied);
return;
}
else
Print("Upper fractals copied",
"i = ",i," copied = ",copied);
}
else Print("Upper fractals copied. ArraySize = ",ArraySize(Ups));
}
IndicatorCreate
The function returns the handle of a specified technical indicator created based on the array of
parameters of MqlParam type.
int IndicatorCreate(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // timeframe
ENUM_INDICATOR indicator_id, // indicator type from the enumeration ENUM_
int parameters_cnt=0, // number of parameters
const MqlParam& parameters_array[]=NULL, // array of parameters
);
Parameters
symbol
[in] Name of a symbol, on data of which the indicator is calculated. NULL means the current
symbol.
period
[in] The value of the timeframe can be one of values of the ENUM_TIMEFRAMES enumeration, 0
means the current timeframe.
indicator_id
[in] Indicator type, can be one of values of the ENUM_INDICATOR enumeration.
parameters_cnt
[in] The number of parameters passed in the parameters_array[] array. The array elements have a
special structure type MqlParam. By default, zero - parameters are not passed. If you specify a
non-zero number of parameters, the parameter parameters_array is obligatory. You can pass no
more than 256 parameters.
parameters_array[]=NULL
[in] An array of MqlParam type, whose elements contain the type and value of each input
parameter of a technical indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
Note
If the indicator handle of IND_CUSTOM type is created, the type field of the first element of the
array of input parameters parameters_array must have the TYPE_STRING value of the
ENUM_DATATYPE enumeration, and the string_value field of the first element must contain the
name of the custom indicator. The custom indicator must be compiled (file with EX5 extension) and
located in the directory MQL5/Indicators of the client terminal or in a subdirectory.
If the first form of the call is used in a custom indicator, you can additionally indicate as the last
parameter on what data it will be calculated when passing input parameters. If the "Apply to"
parameter is not specified explicitly, the default calculation is based on the PRICE_CLOSE values.
Example:
void OnStart()
{
MqlParam params[];
int h_MA,h_MACD;
//--- create iMA("EURUSD",PERIOD_M15,8,0,MODE_EMA,PRICE_CLOSE);
ArrayResize(params,4);
//--- set ma_period
params[0].type =TYPE_INT;
params[0].integer_value=8;
//--- set ma_shift
params[1].type =TYPE_INT;
params[1].integer_value=0;
//--- set ma_method
params[2].type =TYPE_INT;
params[2].integer_value=MODE_EMA;
//--- set applied_price
params[3].type =TYPE_INT;
params[3].integer_value=PRICE_CLOSE;
//--- create MA
h_MA=IndicatorCreate("EURUSD",PERIOD_M15,IND_MA,4,params);
//--- create iMACD("EURUSD",PERIOD_M15,12,26,9,h_MA);
ArrayResize(params,4);
//--- set fast ma_period
params[0].type =TYPE_INT;
params[0].integer_value=12;
//--- set slow ma_period
params[1].type =TYPE_INT;
params[1].integer_value=26;
//--- set smooth period for difference
params[2].type =TYPE_INT;
params[2].integer_value=9;
//--- set indicator handle as applied_price
params[3].type =TYPE_INT;
params[3].integer_value=h_MA;
//--- create MACD based on moving average
h_MACD=IndicatorCreate("EURUSD",PERIOD_M15,IND_MACD,4,params);
//--- use indicators
//--- . . .
//--- release indicators (first h_MACD)
IndicatorRelease(h_MACD);
IndicatorRelease(h_MA);
}
IndicatorRelease
The function removes an indicator handle and release the calculation block of the indicator, if it's not
used by anyone else.
bool IndicatorRelease(
int indicator_handle, // indicator handle
);
Returned value
Note
The function allows removing an indicator handle, if it's no longer needed, thus saving memory. The
handle is removed immediately, the calculation block is deleted in some time (if it's not called
anymore).
Example:
//+------------------------------------------------------------------+
//| Test_IndicatorRelease.mq5 |
//| Copyright 2010, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
//--- input parameters
input int MA_Period=15;
input int MA_shift=0;
input ENUM_MA_METHOD MA_smooth=MODE_SMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
//--- will store indicator handle
int MA_handle=INVALID_HANDLE;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create indicator handle
MA_handle=iMA(Symbol(),0,MA_Period,MA_shift,MA_smooth,PRICE_CLOSE);
//--- delete global variable
if(GlobalVariableCheck("MA_value"))
GlobalVariableDel("MA_value");
//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- if the global variable value does not exist
if(!GlobalVariableCheck("MA_value"))
{
//--- obtain the indicator value in the last two bars
if(MA_handle!=INVALID_HANDLE)
{
//--- dynamic array for the indicator values
double values[];
if(CopyBuffer(MA_handle,0,0,2,values)==2 && values[0]!=EMPTY_VALUE)
{
//--- remember in the global variable value on the last but one bar
if(GlobalVariableSet("MA_value",values[0]))
{
//--- free the handle of the indicator
if(!IndicatorRelease(MA_handle))
Print("IndicatorRelease() failed. Error ",GetLastError());
else MA_handle=INVALID_HANDLE;
}
else
Print("GlobalVariableSet failed. Error ",GetLastError());
}
}
}
//---
}
CopyBuffer
Gets data of a specified buffer of a certain indicator in the necessary quantity.
Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting
position is performed from the present to the past, i.e., starting position of 0 means the current bar
(indicator value for the current bar).
When copying the yet unknown amount of data, it is recommended to use a dynamic array as a buffer
[] recipient buffer, because the CopyBuffer() function tries to allocate the size of the receiving array
to the size of the copied data. If an indicator buffer (array that is pre-allocated for storing indicator
values by the SetIndexBufer() function) is used as the buffer[] recipient array, partial copying is
allowed. An example can be found in the Awesome_Oscillator.mql5 custom indicator in the standard
terminal package.
If you need to make a partial copy of the indicator values into another array (non-indicator buffer),
you should use an intermediate array, to which the desired number is copied. After that conduct the
element-wise copying of the required number of values into the required places if a receiving array
from this intermediate one.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyBuffer(
int indicator_handle, // indicator handle
int buffer_num, // indicator buffer number
int start_pos, // start position
int count, // amount to copy
double buffer[] // target array to copy
);
int CopyBuffer(
int indicator_handle, // indicator handle
int CopyBuffer(
int indicator_handle, // indicator handle
int buffer_num, // indicator buffer number
datetime start_time, // start date and time
datetime stop_time, // end date and time
double buffer[] // target array to copy
);
Parameters
indicator_handle
[in] The indicator handle, returned by the corresponding indicator function.
buffer_num
[in] The indicator buffer number.
start_pos
[in] The position of the first element to copy.
count
[in] Data count to copy.
start_time
[in] Bar time, corresponding to the first element.
stop_time
[in] Bar time, corresponding to the last element.
buffer[]
[out] Array of double type.
Return Value
Note
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration.
Example:
//+------------------------------------------------------------------+
//| TestCopyBuffer3.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot MA
#property indicator_label1 "MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input bool AsSeries=true;
input int period=15;
input ENUM_MA_METHOD smootMode=MODE_EMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
input int shift=0;
//--- indicator buffers
double MABuffer[];
int ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("Parameter AsSeries = ",AsSeries);
Print("Indicator buffer after SetIndexBuffer() is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//--- set short indicator name
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//--- set AsSeries(dependes from input parameter)
ArraySetAsSeries(MABuffer,AsSeries);
Print("Indicator buffer after ArraySetAsSeries(MABuffer,true); is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//---
ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- check if all data calculated
if(BarsCalculated(ma_handle)<rates_total) return(0);
//--- we can copy not all data
int to_copy;
if(prev_calculated>rates_total || prev_calculated<=0) to_copy=rates_total;
else
{
to_copy=rates_total-prev_calculated;
//--- last value is always copied
to_copy++;
}
//--- try to copy
if(CopyBuffer(ma_handle,0,0,to_copy,MABuffer)<=0) return(0);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
The above example illustrates how an indicator buffer is filled out with the values of another indicator
buffer from the indicator on the same symbol/period.
See also
CopyRates
Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the
rates_array array. The elements ordering of the copied data is from present to the past, i.e., starting
position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyRates(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
MqlRates rates_array[] // target array to copy
);
int CopyRates(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
MqlRates rates_array[] // target array to copy
);
int CopyRates(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_time
[in] Bar time for the first element to copy.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
rates_array[]
[out] Array of MqlRates type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
Example:
void OnStart()
{
//---
MqlRates rates[];
ArraySetAsSeries(rates,true);
int copied=CopyRates(Symbol(),0,0,100,rates);
if(copied>0)
{
Print("Bars copied: "+copied);
string format="open = %G, high = %G, low = %G, close = %G, volume = %d";
string out;
int size=fmin(copied,10);
for(int i=0;i<size;i++)
{
out=i+":"+TimeToString(rates[i].time);
out=out+" "+StringFormat(format,
rates[i].open,
rates[i].high,
rates[i].low,
rates[i].close,
rates[i].tick_volume);
Print(out);
}
}
else Print("Failed to get history data for the symbol ",Symbol());
}
See also
Structures and Classes, TimeToString, StringFormat
CopyTime
The function gets to time_array history data of bar opening time for the specified symbol-period pair
in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyTime(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
datetime time_array[] // target array to copy open times
);
int CopyTime(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
datetime time_array[] // target array to copy open times
);
int CopyTime(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time corresponding to the last element to copy.
time_array[]
[out] Array of datetime type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
CopyOpen
The function gets into open_array the history data of bar open prices for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyOpen(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double open_array[] // target array to copy open prices
);
int CopyOpen(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double open_array[] // target array for bar open prices
);
int CopyOpen(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] The start time for the last element to copy.
open_array[]
[out] Array of double type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
CopyHigh
The function gets into high_array the history data of highest bar prices for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyHigh(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double high_array[] // target array to copy
);
int CopyHigh(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double high_array[] // target array to copy
);
int CopyHigh(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
high_array[]
[out] Array of double type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
Example:
#property description "An example for output of the High[i] and Low[i]"
#property description "for a random chosen bars"
double High[],Low[];
//+------------------------------------------------------------------+
//| Get Low for specified bar index |
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double low=0;
ArraySetAsSeries(Low,true);
int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
if(copied>0 && index<copied) low=Low[index];
return(low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index |
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double high=0;
ArraySetAsSeries(High,true);
int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
if(copied>0 && index<copied) high=High[index];
return(high);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- at each tick we output the High and Low values for the bar with index,
//--- equal of the tick second
datetime t=TimeCurrent();
int sec=t%60;
printf("High[%d] = %G Low[%d] = %G",
sec,iHigh(Symbol(),0,sec),
sec,iLow(Symbol(),0,sec));
}
CopyLow
The function gets into low_array the history data of minimal bar prices for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyLow(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double low_array[] // target array to copy
);
int CopyLow(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double low_array[] // target array to copy
);
int CopyLow(
Parameters
symbol_name
[in] Symbol.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] Bar time, corresponding to the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
low_array[]
[out] Array of double type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
See also
CopyHigh
CopyClose
The function gets into close_array the history data of bar close prices for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyClose(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double close_array[] // target array to copy
);
int CopyClose(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double close_array[] // target array to copy
);
int CopyClose(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
close_array[]
[out] Array of double type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
CopyTickVolume
The function gets into volume_array the history data of tick volumes for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyTickVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
long volume_array[] // target array for tick volumes
);
int CopyTickVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
long volume_array[] // target array for tick volumes
);
int CopyTickVolume(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy..
volume_array[]
[out] Array of long type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
Example:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot TickVolume
#property indicator_label1 "TickVolume"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 C'143,188,139'
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=3000;
//--- indicator buffers
double TickVolumeBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,TickVolumeBuffer,INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(prev_calculated==0)
{
long timeseries[];
ArraySetAsSeries(timeseries,true);
int prices=CopyTickVolume(Symbol(),0,0,bars,timeseries);
for(int i=0;i<rates_total-prices;i++) TickVolumeBuffer[i]=0.0;
for(int i=0;i<prices;i++) TickVolumeBuffer[rates_total-1-i]=timeseries[prices-1-i];
Print("We have received the following number of TickVolume values: "+prices);
}
else
{
long timeseries[];
int prices=CopyTickVolume(Symbol(),0,0,1,timeseries);
TickVolumeBuffer[rates_total-1]=timeseries[0];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
CopyRealVolume
The function gets into volume_array the history data of trade volumes for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopyRealVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
long volume_array[] // target array for volumes values
);
int CopyRealVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
long volume_array[] // target array for volumes values
);
int CopyRealVolume(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
volume_array[]
[out] Array of long type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
CopySpread
The function gets into spread_array the history data of spread values for the selected symbol-period
pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e.,
starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target
array, because if the requested data count is less (or more) than the length of the target array,
function tries to reallocate the memory so that the requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
int CopySpread(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
int spread_array[] // target array for spread values
);
int CopySpread(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
int spread_array[] // target array for spread values
);
int CopySpread(
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
spread_array[]
[out] Array of int type.
Return Value
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
When requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
When requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
When requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value
is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos=0 and count=1.
Example:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Spread
#property indicator_label1 "Spread"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=3000;
//--- indicator buffers
double SpreadBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,SpreadBuffer,INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(prev_calculated==0)
{
int spread_int[];
ArraySetAsSeries(spread_int,true);
int spreads=CopySpread(Symbol(),0,0,bars,spread_int);
Print("We have received the following number of Spread values: ",spreads);
for (int i=0;i<spreads;i++)
{
SpreadBuffer[rates_total-1-i]=spread_int[i];
if(i<=30) Print("spread["+i+"] = ",spread_int[i]);
}
}
else
{
double Ask,Bid;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Comment("Ask = ",Ask," Bid = ",Bid);
SpreadBuffer[rates_total-1]=(Ask-Bid)/Point();
}
//--- return value of prev_calculated for next call
return(rates_total);
}
Chart Operations
These are functions for working with charts. All chart operations are allowed in Expert Advisors and
scripts only.
Function Action
ChartApplyTemplate
Applies a specific template from a specified file to the chart.
bool ChartApplyTemplate(
long chart_id, // Chart ID
const string filename // Template file name
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] The name of the file containing the template.
Return Value
If a template is applied successfully, the function returns true, otherwise false. To get an
information about the error, call the GetLastError() function.
Note
The Expert Advisor will be unloaded and will not be able to continue operating in case of successful
loading of a new template to the chart it is attached to.
Using Templates
The resources of the MQL5 language allow setting multiple chart properties, including colors using the
ChartSetInteger() function:
Besides, there can be multiple graphical objects and indicators on a chart. You may set up a chart with
all the necessary indicators once and then save it as a template. Such a template can be applied to any
chart.
The ChartApplyTemplate() function is intended for using a previously saved template, and it can be
used in any mql5 program. The path to the file that stores the template is passed as the second
parameter to ChartApplyTemplate(). The template file is searched according to the following rules:
if the backslash "\" separator (written as "\\") is placed at the beginning of the path, the template
is searched for relative to the path _terminal_data_directory\MQL5,
if there is no backslash, the template is searched for relative to the executable EX5 file, in which
ChartApplyTemplate() is called;
if a template is not found in the first two variants, the search is performed in the folder
terminal_directory\Profiles\Templates\.
Here terminal_directory is the folder from which the MetaTrader 5 Client Terminal is running, and
terminal_data_directory is the folder, in which editable files are stored, its location depends on the
operating system, user name and computer's security settings. Normally they are different folders, but
in some cases they may coincide.
The location of folders terminal_data_directory and terminal_directory can be obtained using the
TerminalInfoString() function.
//--- directory from which the terminal is started
string terminal_path=TerminalInfoString(TERMINAL_PATH);
Print("Terminal directory:",terminal_path);
//--- terminal data directory, in which the MQL5 folder with EAs and indicators is located
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
Print("Terminal data directory:",terminal_data_path);
For example:
Templates are not resources, they cannot be included into an executable EX5 file.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Let's open and try to apply 'my_template.tpl' template
if(!ChartApplyTemplate(0,"my_template"))
{
//--- If unable to apply template, then
Print("Unable to apply 'my_template', error ",GetLastError());
ResetLastError();
}
else
{
//--- Template is stored in file without extension
Print("'my_template' successfully applied - file without extension");
}
}
See also
Resources
ChartWindowFind
The function returns the number of a subwindow where an indicator is drawn. There are 2 variants of
the function.
1. The function searches in the indicated chart for the subwindow with the specified "short name" of
the indicator (the short name is displayed in the left top part of the subwindow), and it returns the
subwindow number in case of success.
int ChartWindowFind(
long chart_id, // chart identifier
string indicator_shortname // short indicator name, see INDICATOR_SHORTNAME
2. The function must be called from a custom indicator. It returns the number of the subwindow where
the indicator is working.
int ChartWindowFind();
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
indicator_shortname
[in] Short name of the indicator.
Return Value
Subwindow number in case of success. In case of failure the function returns -1.
Note
If the second variant of the function (without parameters) is called from a script or Expert Advisor,
the function returns -1.
Don't mix up the short name of an indicator and a file name, which is specified when an indicator is
created using iCustom() and IndicatorCreate() functions. If the indicator's short name is not set
explicitly, then the name of the file containing the source code of the indicator, is specified in it
during compilation.
It is important to correctly form the short name of an indicator, which is recorded in the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that
the short name contains values of the indicator's input parameters, because the indicator deleted
from a chart in the ChartIndicatorDelete() function is identified by its short name.
Exapmle:
#property script_show_inputs
//--- input parameters
input string shortname="MACD(12,26,9)";
//+------------------------------------------------------------------+
//| returns number of the chart window with this indicator |
//+------------------------------------------------------------------+
int GetIndicatorSubWindowNumber(long chartID=0,string short_name="")
{
int window=-1;
//---
if((ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR)
{
//--- the function is called from the indicator, name is not required
window=ChartWindowFind();
}
else
{
//--- the function is called from an Expert Advisor or script
window=ChartWindowFind(0,short_name);
if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError());
}
//---
return(window);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int window=GetIndicatorSubWindowNumber(0,shortname);
if(window!=-1)
Print("Indicator "+shortname+" is in the window #"+(string)window);
else
Print("Indicator "+shortname+" is not found. window = "+(string)window);
}
See also
ObjectCreate(), ObjectFind()
ChartOpen
Opens a new chart with the specified symbol and period.
long ChartOpen(
string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);
Parameters
symbol
[in] Chart symbol. NULL means the symbol of the current chart (the Expert Advisor is attached
to).
period
[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current
chart period.
Return Value
Note
The maximum possible number of simultaneously open charts in the terminal can't exceed the
CHARTS_MAX value.
ChartFirst
Returns the ID of the first chart of the client terminal.
long ChartFirst();
Return Value
Chart ID.
ChartNext
Returns the chart ID of the chart next to the specified one.
long ChartNext(
long chart_id // Chart ID
);
Parameters
chart_id
[in] Chart ID. 0 does not mean the current chart. 0 means "return the first chart ID".
Return Value
Chart ID. If this is the end of the chart list, it returns -1.
Example:
ChartClose
Closes the specified chart.
bool ChartClose(
long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
ChartSymbol
Returns the symbol name for the specified chart.
string ChartSymbol(
long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
See also
ChartSetSymbolPeriod
ChartPeriod
Returns the timeframe period of specified chart.
ENUM_TIMEFRAMES ChartPeriod(
long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
The function returns one of the ENUM_TIMEFRAMES values. If chart does not exist, it returns 0.
ChartRedraw
This function calls a forced redrawing of a specified chart.
void ChartRedraw(
long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Note
See also
Objects functions
ChartSetDouble
Sets a value for a corresponding property of the specified chart. Chart property should be of a double
type.
bool ChartSetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
double value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. Can be one of the ENUM_CHART_PROPERTY_DOUBLE values (except the
read-only properties).
value
[in] Property value.
Return Value
ChartSetInteger
Sets a value for a corresponding property of the specified chart. Chart property must be
datetime, int, color, bool or char.
bool ChartSetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
long value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. It can be one of the ENUM_CHART_PROPERTY_INTEGER value (except the
read-only properties).
value
[in] Property value.
Return Value
ChartSetString
Sets a value for a corresponding property of the specified chart. Chart property must be of the string
type.
bool ChartSetString(
long chart_id, // Chart ID
int prop_id, // Property ID
string str_value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. It's value can be one of the ENUM_CHART_PROPERTY_STRING values
(except the read-only properties).
str_value
[in] Property value string. String length cannot exceed 2045 characters (extra characters will be
truncated).
Return Value
Note
ChartSetString can be used for a comment output on the chart instead of the Comment function.
Example:
void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
string comment=StringFormat("Printing prices:\nAsk = %G\nBid = %G\nSpread = %d",
Ask,Bid,Spread);
ChartSetString(0,CHART_COMMENT,comment);
}
See also
Comment, ChartGetString
ChartGetDouble
Returns the value of a corresponding property of the specified chart. Chart property must be of double
type. There are 2 variants of th efunction calls.
double ChartGetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);
2. Returns true or false, depending on the success of a function. If successful, the value of the
property is placed in a target variable double_var passed by reference.
bool ChartGetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window, // Subwindow number
double& double_var // Target variable for the chart property
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_DOUBLE values.
sub_window
[in] Number of the chart subwindow. For the first case, the default value is 0 (main chart
window). The most of the properties do not require a subwindow number.
double_var
[out] Target variable of double type for the requested property.
Return Value
For the second call case it returns true if the specified property is available and its value has been
placed into double_var variable, otherwise returns false. To get an additional information about the
error, it is necessary to call the function GetLastError().
Example:
void OnStart()
{
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,0);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,0);
Print("CHART_PRICE_MIN =",priceMin);
Print("CHART_PRICE_MAX =",priceMax);
}
ChartGetInteger
Returns the value of a corresponding property of the specified chart. Chart property must be of
datetime, int or bool type. There are 2 variants of the function calls.
long ChartGetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);
2. Returns true or false, depending on the success of a function. If successful, the value of the
property is placed in a target variable long_var passed by reference.
bool ChartGetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window, // subwindow number
long& long_var // Target variable for the property
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_INTEGER values.
sub_window
[in] Number of the chart subwindow. For the first case, the default value is 0 (main chart
window). The most of the properties do not require a subwindow number.
long_var
[out] Target variable of long type for the requested property.
Return Value
For the second call case it returns true if specified property is available and its value has been
stored into long_var variable, otherwise returns false. To get additional information about the error
, it is necessary to call the function GetLastError().
Example:
void OnStart()
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
Print("CHART_HEIGHT_IN_PIXELS =",height,"pixels");
Print("CHART_WIDTH_IN_PIXELS =",width,"pixels");
}
ChartGetString
Returns the value of a corresponding property of the specified chart. Chart property must be of string
type. There are 2 variants of the function call.
string ChartGetString(
long chart_id, // Chart ID
int prop_id // Property ID
);
2. Returns true or false, depending on the success of a function. If successful, the value of the
property is placed in a target variable string_var passed by reference.
bool ChartGetString(
long chart_id, // Chart ID
int prop_id, // Property ID
string& string_var // Target variable for the property
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_STRING values.
string_var
[out] Target variable of string type for the requested property.
Return Value
For the second call case it returns true if the specified property is available and its value has been
stored into string_var variable, otherwise returns false. To get additional information about the
error, it is necessary to call the function GetLastError().
Note
ChartGetString can be used for reading comments plotted on the chart using the Comment or
ChartSetString functions.
Example:
void OnStart()
{
ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!");
ChartRedraw();
Sleep(1000);
string comm=ChartGetString(0,CHART_COMMENT);
Print(comm);
See also
Comment, ChartSetString
ChartNavigate
Performs shift of the specified chart by the specified number of bars relative to the specified position
in the chart.
bool ChartNavigate(
long chart_id, // Chart ID
int position, // Position
int shift=0 // Shift value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
position
[in] Chart position to perform a shift. Can be one of the ENUM_CHART_POSITION values.
shift=0
[in] Number of bars to shift the chart. The positive value means the right shift (to the end if the
chart), the negative value means the left shift (to the chart begin). The zero shift can be used to
navigate to chart beginning or end.
Return Value
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get handle of the current chart
long handle=ChartID();
string comm="";
if(handle>0) // if successful, additionally set up
{
//--- disable auto scroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- set a shift from the right chart border
ChartSetInteger(handle,CHART_SHIFT,true);
//--- draw candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- set the display mode for tick volumes
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
Comment(comm);
}
}
ChartID
Returns the ID of the current chart.
long ChartID();
Return Value
ChartIndicatorAdd
Adds an indicator with the specified handle into a specified chart window.
bool ChartIndicatorAdd(
long chart_id, // chart ID
int sub_window // number of the sub-window
int indicator_handle // handle of the indicator
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart sub-window. 0 means the main chart window. if the number of a
not-existing window is specified, a new window will be created.
indicator_handle
[in] The handle of the indicator.
Return Value
The function returns true in case of success, otherwise it returns false. In order to obtain
information about the error, call the GetLastError() function.
See Also
ChartIndicatorDelete(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate()
ChartIndicatorDelete
Removes an indicator with a specified name from the specified chart window.
bool ChartIndicatorDelete(
long chart_id, // chart id
int sub_window // number of the subwindow
const string ind_shortname // short name of the indicator
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
const ind_shortname
[in] The short name of the indicator which is set in the INDICATOR_SHORTNAME property with
the IndicatorSetString() function. To get the short name of an indicator use the
ChartIndicatorName() function.
Return Value
Returns true in case of successful deletion of the indicator. Otherwise it returns false. To get error
details use the GetLastError() function.
Note
If two indicators with identical short names exist in the chart subwindow, the first one in a row will
be deleted.
If other indicators on this chart are based on the values of the indicator that is being deleted, such
indicators will also be deleted.
Do not confuse the indicator short name and the file name that is specified when creating an
indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not
set explicitly, then the name of the file containing the source code of the indicator will be specified
during compilation.
Deletion of an indicator from a chart doesn't mean that its calculation part will be deleted from the
terminal memory. To release the indicator handle use the IndicatorRelease() function.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that
the short name should contain values of all the input parameters of the indicator, because the
indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the
short name.
See also
ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorSetString()
ChartIndicatorName
Returns the short name of the indicator by the number in the indicators list on the specified chart
window.
string ChartIndicatorName(
long chart_id, // chart id
int sub_window // number of the subwindow
int index // index of the indicator in the list of indicators added to the chat subwi
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
index
[in] the index of the indicator in the list of indicators. The numeration of indicators start with
zero, i.e. the first indicator in the list has the 0 index. To obtain the number of indicators in the
list use the ChartIndicatorsTotal() function.
Return Value
The short name of the indicator which is set in the INDICATOR_SHORTNAME property with the
IndicatorSetString() function. To get error details use the GetLastError() function.
Note
Do not confuse the indicator short name and the file name that is specified when creating an
indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not
set explicitly, then the name of the file containing the source code of the indicator will be specified
during compilation.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that
the short name should contain values of all the input parameters of the indicator, because the
indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the
short name.
See also
ChartIndicatorAdd(), ChartIndicatorDelete(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorSetString()
ChartIndicatorsTotal
Returns the number of all indicators applied to the specified chart window.
int ChartIndicatorsTotal(
long chart_id, // chart id
int sub_window // number of the subwindow
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
Return Value
The number of indicators in the specified chart window. To get error details use the GetLastError()
function.
Note
The function allows going searching through all the indicators attached to the chart. The number of
all the windows of the chart can be obtained from the CHART_WINDOWS_TOTAL property using the
ChartGetInteger() function.
See also
ChartIndicatorAdd(), ChartIndicatorDelete(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorSetString()
ChartWindowOnDropped
Returns the number (index) of the chart subwindow, the Expert Advisor or script has been dropped to.
0 means the main chart window.
int ChartWindowOnDropped();
Return Value
Example:
int myWindow=ChartWindowOnDropped();
int windowsTotal=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("Script is running on the window #"+myWindow+
". Total windows on the chart "+ChartSymbol()+":",windowsTotal);
See also
ChartPriceOnDropped, ChartTimeOnDropped, ChartXOnDropped, ChartYOnDropped
ChartPriceOnDropped
Returns the price coordinate corresponding to the chart point, an Expert Advisor or script has been
dropped to.
double ChartPriceOnDropped();
Return Value
Example:
double p=ChartPriceOnDropped();
Print("ChartPriceOnDropped() = ",p);
See also
ChartXOnDropped, ChartYOnDropped
ChartTimeOnDropped
Returns the time coordinate corresponding to the chart point, an Expert Advisor or script has been
dropped to.
datetime ChartTimeOnDropped();
Return Value
Example:
datetime t=ChartTimeOnDropped();
Print("Script was dropped on the "+t);
See also
ChartXOnDropped, ChartYOnDropped
ChartXOnDropped
Returns the X coordinate of the chart point, an Expert Advisor or script has been dropped to.
int ChartXOnDropped();
Return Value
Note
Example:
int X=ChartXOnDropped();
int Y=ChartYOnDropped();
Print("(X,Y) = ("+X+","+Y+")");
See also
ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped
ChartYOnDropped
Returns the Y coordinateof the chart point, an Expert Advisor or script has been dropped to.
int ChartYOnDropped();
Return Value
Note
See also
ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped
ChartSetSymbolPeriod
Changes the symbol and period of the specified chart. The function is asynchronous, i.e. it sends the
command and does not wait for its execution completion.
bool ChartSetSymbolPeriod(
long chart_id, // Chart ID
string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
symbol
[in] Chart symbol. NULL value means the current chart symbol (Expert Advisor is attached to)
period
[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current
chart period.
Return Value
Note
The symbol/period change leads to the re-initialization of the Expert Advisor, attached to a chart.
See also
ChartSymbol, ChartPeriod
ChartScreenShot
The function provides a screenshot of the chart in its current state in a gif format.
bool ChartScreenShot(
long chart_id, // Chart ID
string filename, // Symbol name
int width, // Width
int height, // Height
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT // Alignment type
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in the
directory \ Files.
width
[in] Screenshot width in pixels.
height
[in] Screenshot height in pixels.
align_mode=ALIGN_RIGHT
[in] Output mode of a narrow screenshot. ALIGN_RIGHT means align to the right margin (the
output from the end). ALIGN_LEFT means Left justify.
Return Value
Note
If you need to take a screenshot from a chart from a certain position, first it's necessary to position
the graph using the ChartNavigate() function. If the horizontal size of the screenshot is smaller than
the chart window, either the right part of the chart window, or its left part is output, depending on
the align_mode settings.
Trade Functions
This is the group of functions intended for managing trading activities.
Trading functions can be used in Expert Advisors and scripts. Trading functions can be called only if in
the properties of the Expert Advisor or script the "Allow live trading" checkbox is enabled.
Function Action
working with it
OrderCalcMargin
The function calculates the margin required for the specified order type, on the current account, in
the current market environment not taking into account current pending orders and open positions. It
allows the evaluation of margin for the trade operation planned. The value is returned in the account
currency.
bool OrderCalcMargin(
ENUM_ORDER_TYPE action, // type of order
string symbol, // symbol name
double volume, // volume
double price, // open price
double& margin // value for obtaining the margin value
);
Parameters
action
[in] The order type, can be one of the valued of the ENUM_ORDER_TYPE enumeration.
symbol
[in] Symbol name.
volume
[in] Volume of the trade operation.
price
[in] Open price.
margin
[out] The variable, to which the value of the required margin will be written in case the function
is successfully executed. The calculation is performed as if there were no pending orders and open
positions on the current account. The margin value depends on many factors, and can differ in
different market environments.
Return Value
The function returns true in case of success; otherwise it returns false. In order to obtain
information about the error, call the GetLastError() function.
See also
OrderSend(), Order Properties, Trade Operation Types
OrderCalcProfit
The function calculates the profit for the current account, in the current market conditions, based on
the parameters passed. The function is used for pre-evaluation of the result of a trade operation. The
value is returned in the account currency.
bool OrderCalcProfit(
ENUM_ORDER_TYPE action, // type of the order (ORDER_TYPE_BUY or ORDER_TYPE_SELL)
string symbol, // symbol name
double volume, // volume
double price_open, // open price
double price_close, // close price
double& profit // variable for obtaining the profit value
);
Parameters
action
[in] Type of the order, can be one of the two values of the ENUM_ORDER_TYPE enumeration:
ORDER_TYPE_BUY or ORDER_TYPE_SELL.
symbol
[in] Symbol name.
volume
[in] Volume of the trade operation.
price_open
[in] Open price.
price_close
[in] Close price.
profit
[out] The variable, to which the calculated value of the profit will be written in case the function
is successfully executed. The estimated profit value depends on many factors, and can differ in
different market environments.
Return Value
The function returns true in case of success; otherwise it returns false. If an invalid order type is
specified, the function will return false. In order to obtain information about the error, call
GetLastError().
See also
OrderSend(), Order Properties, Trade Operation Types
OrderCheck
The OrderCheck() function checks if there are enough money to execute a required trade operation.
The check results are placed tothe fields of the MqlTradeCheckResult structure.
bool OrderCheck(
MqlTradeRequest& request, // request structure
MqlTradeCheckResult& result // result structure
);
Parameters
request
[in] Pointer to the structure of the MqlTradeRequest type, which describes the required trade
action.
result
[in,out] Pointer to the structure of the MqlTradeCheckResult type, to which the check result will
be placed.
Return Value
If funds are not enough for the operation, or parameters are filled out incorrectly, the function
returns false. In case of a successful basic check of structures (check of pointers), it returns true –
this is not an indication that the requested trade operation is sure to be successfully executed.
For a more detailed description of the function execution result, analyze the fields of the result
structure.
In order to obtain information about the error, call the GetLastError() function.
See also
OrderSend(), Trade Operation Types, Trade Request Structure, Structure of Request Check Results,
Structure of a Trade Request Result
OrderSend
The OrderSend() function is used for executing trade operations by sending requests to a trade
server.
bool OrderSend(
MqlTradeRequest& request, // query structure
MqlTradeResult& result // structure of the answer
);
Parameters
request
[in] Pointer to a structure of MqlTradeRequest type describing the trade activity of the client.
result
[in,out] Pointer to a structure of MqlTradeResult type describing the result of trade operation in
case of a successful completion (if true is returned).
Return Value
In case of a successful basic check of structures (index checking) returns true – this is not a sign of
successful execution of a trade operation. For a more detailed description of the function
execution result, analyze the fields of result structure.
Note
The trade requests go through several stages of checking on a trade server. First of all, it checks if
all the required fields of the request parameter are filled out correctly. If there are no errors, the
server accepts the order for further processing. If the order is successfully accepted by the trade
server, the OrderSend() function returns true.
It is recommended to check the request before sending it to a trade server. To check requests, use
the OrderCheck() function. It checks if there are enough funds to execute the trade operation, and
returns many useful parameters in the results of trade request checking:
return code containing information about errors in the checked request;
balance value that will appear after the trade operation is executed;
equity value that will appear after the trade operation is executed;
floating point value that will appear after the trade operation is executed;
margin required for the trade operation;
amount of free equity that will remain after the execution of the trade operation;
the margin level that will be set after the trade operation is executed;
comment to the reply code, error description.
It should be noted when placing a market order that the successful completion of the OrderSend()
method operation does not always mean a successful deal completion. Check in the returned result
structure result the retcode value containing trade server return code, and values of deal or order
field depending on the type of operation.
Each accepted order is stored on the trade server awaiting processing until one of the conditions for
its execution occurs:
expiration,
At the moment of the order processing, the trade server sends to the terminal a message about the
occurrence of the Trade event, which can be processed by the OnTrade() function.
Example:
//+------------------------------------------------------------------+
//| deletes all pending orders with specified ORDER_MAGIC |
//+------------------------------------------------------------------+
void DeleteAllOrdersByMagic(long const magic_number)
{
long order_ticket;
int total=0;
//--- selection through the entire history
HistorySelect(0,TimeCurrent());
//--- go through all pending orders
for(int i=OrdersTotal()-1;i>=0;i--)
if(order_ticket=OrderGetTicket(i))
//--- order with appropriate ORDER_MAGIC
if(magic_number==OrderGetInteger(ORDER_MAGIC))
{
MqlTradeResult result;
MqlTradeRequest request;
request.order=order_ticket;
request.action=TRADE_ACTION_REMOVE;
OrderSend(request,result);
//--- write the server reply to log
Print(__FUNCTION__,": ",result.comment," reply code ",result.retcode);
}
//---
}
//+------------------------------------------------------------------+
//| set a pending order in a random way |
//+------------------------------------------------------------------+
int SendRandomPendingOrder(long const magic_number)
{
//--- prepare a request
MqlTradeRequest request;
request.action=TRADE_ACTION_PENDING; // setting a pending order
request.magic=magic_number; // ORDER_MAGIC
request.symbol=_Symbol; // symbol
request.volume=0.1; // volume in 0.1 lots
request.sl=0; // Stop Loss is not specified
request.tp=0; // Take Profit is not specified
request.deviation=5; // deviation in 5 points
//--- form the order type
request.type=GetRandomType(); // order type
//--- form the price for the pending order
request.price=GetRandomPrice(request.type); // open price
//--- send a trade request
MqlTradeResult result;
OrderSend(request,result);
//--- write the server reply to log
Print(__FUNCTION__,":",result.comment);
if(result.retcode==10016) Print(result.bid,result.ask,result.price);
//--- return code of the trade server reply
return result.retcode;
}
//+------------------------------------------------------------------+
//| return type of a pending order in a random way |
//+------------------------------------------------------------------+
ENUM_ORDER_TYPE GetRandomType()
{
int t=MathRand()%4;
//--- 0<=t<4
switch(t)
{
case(0):return(ORDER_TYPE_BUY_LIMIT);
case(1):return(ORDER_TYPE_SELL_LIMIT);
case(2):return(ORDER_TYPE_BUY_STOP);
case(3):return(ORDER_TYPE_SELL_STOP);
}
//--- incorrect value
return(WRONG_VALUE);
//---
}
//+------------------------------------------------------------------+
//| return price in a random way |
//+------------------------------------------------------------------+
double GetRandomPrice(ENUM_ORDER_TYPE type)
{
int t=(int)type;
//--- stop levels for the symbol
int distance=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
//--- receive data of the last tick
MqlTick last_tick;
SymbolInfoTick(_Symbol,last_tick);
//--- calculate price according to the type
double price;
if(t==2 || t==5) // ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_STOP
{
price=last_tick.bid; // depart from price Bid
price=price-(distance+(MathRand()%10)*5)*_Point;
}
else // ORDER_TYPE_SELL_LIMIT or ORDER_TYPE_BUY_STOP
{
price=last_tick.ask; // depart from price Ask
price=price+(distance+(MathRand()%10)*5)*_Point;
}
return(price);
}
See also
Trade Operation Types, Trade Request Structure, Structure of Request Check Results, Structure of a
Trade Request Result
PositionsTotal
Returns the number of open positions.
int PositionsTotal();
Return Value
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse current pending orders with positions, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
The total number of positions on a trade account cannot exceed the total number of financial
instruments.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
PositionGetSymbol
Returns the symbol corresponding to the open position and automatically selects the position for
further working with it using functions PositionGetDouble, PositionGetInteger, PositionGetString.
string PositionGetSymbol(
int index // Number in the list of positions
);
Parameters
index
[in] Number of the position in the list of open positions.
Return Value
Value of the string type. If the position was not found, an empty string will be returned. To get an
error code, call the GetLastError() function.
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse current pending orders with positions, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
The total number of positions on a trade account cannot exceed the total number of financial
instruments.
See also
PositionsTotal(), PositionSelect(), Position Properties
PositionSelect
Chooses an open position for further working with it. Returns true if the function is successfully
completed. Returns false in case of failure. To obtain information about the error, call GetLastError().
bool PositionSelect(
string symbol // Symbol name
);
Parameters
symbol
[in] Name of the financial security.
Return Value
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse positions with current pending orders, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
Function PositionSelect() copies data about a position into the program environment, and further
calls of PositionGetDouble(), PositionGetInteger() and PositionGetString() return the earlier copied
data. This means that the position itself may no longer exist (or it's volume, direction, etc. has
changed), but data of this position still can be obtained. To ensure receipt of fresh data about a
position, it is recommended to call PositionSelect() right before referring to them.
See also
PositionGetSymbol(), PositionsTotal(), Position Properties
PositionGetDouble
The function returns the requested property of an open position, pre-selected using PositionGetSymbol
or PositionSelect. The position property must be of the double type. There are 2 variants of the
function.
double PositionGetDouble(
ENUM_POSITION_PROPERTY_DOUBLE property_id // Property identifier
);
2. Returns true or false, depending on the success of the function execution. If successful, the value
of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetDouble(
ENUM_POSITION_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of a position property. The value can be one of the values of the
ENUM_POSITION_PROPERTY_DOUBLE enumeration.
double_var
[out] Variable of the double type, accepting the value of the requested property.
Return Value
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse positions with current pending orders, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
PositionGetInteger
The function returns the requested property of an open position, pre-selected using PositionGetSymbol
or PositionSelect. The position property should be of datetime, int type. There are 2 variants of the
function.
long PositionGetInteger(
ENUM_POSITION_PROPERTY_INTEGER property_id // Property identifier
);
2. Returns true or false, depending on the success of the function execution. If successful, the value
of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetInteger(
ENUM_POSITION_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of a position property. The value can be one of the values of the
ENUM_POSITION_PROPERTY_INTEGER enumeration.
long_var
[out] Variable of the long type accepting the value of the requested property.
Return Value
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse positions with current pending orders, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
PositionGetString
The function returns the requested property of an open position, pre-selected using PositionGetSymbol
or PositionSelect. The position property should be of the string type. There are 2 variants of the
function.
string PositionGetString(
ENUM_POSITION_PROPERTY_STRING property_id // Property identifier
);
2. Returns true or false, depending on the success of the function execution. If successful, the value
of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetString(
ENUM_POSITION_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of a position property. The value can be one of the values of the
ENUM_POSITION_PROPERTY_STRING enumeration.
string_var
[out] Variable of the string type accepting the value of the requested property.
Return Value
Value of the string type. If the function fails, an empty string is returned.
Note
For each symbol, at any given moment of time, only one position can be open, which is the result of
one or more deals. Do not confuse positions with current pending orders, which are also displayed
on the "Trade" tab of the "Toolbox" of the client terminal.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
OrdersTotal
Returns the number of current orders.
int OrdersTotal();
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For each symbol, at any given moment of time, only one position can be open, while there can be
several pending orders for the same symbol.
See also
OrderSelect(), OrderGetTicket(), Order Properties
OrderGetTicket
Returns ticket of a corresponding order automatically selects the order for further working with it
using functions.
ulong OrderGetTicket(
int index // Number in the list of orders
);
Parameters
index
[in] Number of an order in the list of current orders.
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For each symbol, at any given moment of time, only one position can be open, while there can be
several pending orders for the same symbol.
Function OrderGetTicket() copies data about an order into the program environment, and further
calls of OrderGetDouble(), OrderGetInteger(), OrderGetString() return the earlier copied data. This
means that the order itself may no longer exist (or its open price, Stop Loss/Take Profit levels or
expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data
about an order, it is recommended to call OrderGetTicket() right before referring to them.
Example:
void OnStart()
{
datetime from=0;
datetime to=TimeCurrent();
//--- request the entire history
HistorySelect(from,to);
//--- variables for returning values from order properties
ulong ticket;
double open_price;
double initial_volume;
datetime time_setup;
string symbol;
string type;
long order_magic;
long positionID;
//--- number of current pending orders
uint total=OrdersTotal();
//--- go through orders in a loop
for(uint i=0;i<total;i++)
{
//--- return order ticket by its position in the list
if((ticket=OrderGetTicket(i))>0)
{
//--- return order properties
open_price= OrderGetDouble(ORDER_PRICE_OPEN);
time_setup= OrderGetInteger(ORDER_TIME_SETUP);
symbol= OrderGetString(ORDER_SYMBOL);
order_magic= OrderGetInteger(ORDER_MAGIC);
positionID = OrderGetInteger(ORDER_POSITION_ID);
initial_volume= OrderGetDouble(ORDER_VOLUME_INITIAL);
type=GetOrderType(OrderGetInteger(ORDER_TYPE));
//--- prepare and show information about the order
printf("#ticket %d %s %G %s at %G was set up at %s",
ticket, // order ticket
type, // type
initial_volume, // placed volume
symbol, // symbol
open_price, // specified open price
TimeToString(time_setup)// time of order placing
);
}
}
//---
}
//+------------------------------------------------------------------+
//| returns the string name of the order type |
//+------------------------------------------------------------------+
string GetOrderType(long type)
{
string str_type="unknown operation";
switch(type)
{
case (ORDER_TYPE_BUY): return("buy");
case (ORDER_TYPE_SELL): return("sell");
case (ORDER_TYPE_BUY_LIMIT): return("buy limit");
case (ORDER_TYPE_SELL_LIMIT): return("sell limit");
case (ORDER_TYPE_BUY_STOP): return("buy stop");
case (ORDER_TYPE_SELL_STOP): return("sell stop");
case (ORDER_TYPE_BUY_STOP_LIMIT): return("buy stop limit");
case (ORDER_TYPE_SELL_STOP_LIMIT):return("sell stop limit");
}
return(str_type);
}
See also
OrdersTotal(), OrderSelect(), OrderGetInteger()
OrderSelect
Selects an order to work with. Returns true if the function has been successfully completed. Returns
false if the function completion has failed. For more information about an error call GetLastError().
bool OrderSelect(
ulong ticket // Order ticket
);
Parameters
ticket
[in] Order ticket.
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one
position can be open, while there can be several pending orders for the same symbol.
Function OrderSelect() copies data about an order into the program environment, and further calls
of OrderGetDouble(), OrderGetInteger(), OrderGetString() return the earlier copied data. This
means that the order itself may no longer exist (or its open price, Stop Loss/Take Profit levels or
expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data
about an order, it is recommended to call OrderSelect() right before referring to them.
See also
OrderGetInteger(), OrderGetDouble(), OrderGetString(), OrderCalcProfit(), OrderGetTicket(), Order
Properties
OrderGetDouble
Returns the requested property of an order, pre-selected using OrderGetTicket or OrderSelect. The
order property must be of the double type. There are 2 variants of the function.
double OrderGetDouble(
ENUM_ORDER_PROPERTY_DOUBLE property_id // Property identifier
);
2. Returns true or false, depending on the success of a function. If successful, the value of the
property is placed in a target variable passed by reference by the last parameter.
bool OrderGetDouble(
ENUM_ORDER_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_DOUBLE enumeration.
double_var
[out] Variable of the double type that accepts the value of the requested property.
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one
position can be open, while there can be several pending orders for the same symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before
referring to them.
See also
OrdersTotal(), OrderGetTicket(), Order Properties
OrderGetInteger
Returns the requested order property, pre-selected using OrderGetTicket or OrderSelect. Order
property must be of the datetime, int type. There are 2 variants of the function.
long OrderGetInteger(
ENUM_ORDER_PROPERTY_INTEGER property_id // Property identifier
);
2. Returns true or false depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool OrderGetInteger(
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_INTEGER enumeration.
long_var
[out] Variable of the long type that accepts the value of the requested property.
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one
position can be open, while there can be several pending orders for the same symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before
referring to them.
See also
OrdersTotal(), OrderGetTicket(), Order Properties
OrderGetString
Returns the requested order property, pre-selected using OrderGetTicket or OrderSelect. The order
property must be of the string type. There are 2 variants of the function.
string OrderGetString(
ENUM_ORDER_PROPERTY_STRING property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool OrderGetString(
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_STRING enumeration.
string_var
[out] Variable of the string type that accepts the value of the requested property.
Return Value
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one
position can be open, while there can be several pending orders for the same symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before
referring to them.
See also
OrdersTotal(), OrderGetTicket(), Order Properties
HistorySelect
Retrieves the history of deals and orders for the specified period of server time.
bool HistorySelect(
datetime from_date, // From date
datetime to_date // To date
);
Parameters
from_date
[in] Start date of the request.
to_date
[in] End date of the request request.
Return Value
Note
HistorySelect() creates a list of orders and a list of trades in a mql5-program, for further referring
to the list elements using corresponding functions. The deals list size can be returned using the
HistoryDealsTotal() function; the size of the list of orders in the history can be obtained using
HistoryOrdersTotal(). Selection in the list of orders should be better performed by
HistoryOrderGetTicket(), for items in the list of deals HistoryDealGetTicket() suits better.
After using HistoryOrderSelect(), the list of history orders available to the mql5 program is reset
and filled again by the found order, if the search of an order by the ticket has been completed
successfully. The same applies to the list of deals available to the mql5 program - it is reset by
HistoryDealSelect() and filled again in case of a successful receipt of a deal by ticket number.
Example:
void OnStart()
{
color BuyColor =clrBlue;
color SellColor=clrRed;
//--- request trade history
HistorySelect(0,TimeCurrent());
//--- create objects
string name;
uint total=HistoryDealsTotal();
ulong ticket=0;
double price;
double profit;
datetime time;
string symbol;
long type;
long entry;
//--- for all deals
for(uint i=0;i<total;i++)
{
//--- try to get deals ticket
if(ticket=HistoryDealGetTicket(i))
{
//--- get deals properties
price =HistoryDealGetDouble(ticket,DEAL_PRICE);
time =HistoryDealGetInteger(ticket,DEAL_TIME);
symbol=HistoryDealGetString(ticket,DEAL_SYMBOL);
type =HistoryDealGetInteger(ticket,DEAL_TYPE);
entry =HistoryDealGetInteger(ticket,DEAL_ENTRY);
profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
//--- only for current symbol
if(price && time && symbol==Symbol())
{
//--- create price object
name="TradeHistory_Deal_"+string(ticket);
if(entry) ObjectCreate(0,name,OBJ_ARROW_RIGHT_PRICE,0,time,price,0,0);
else ObjectCreate(0,name,OBJ_ARROW_LEFT_PRICE,0,time,price,0,0);
//--- set object properties
ObjectSetInteger(0,name,OBJPROP_SELECTABLE,0);
ObjectSetInteger(0,name,OBJPROP_BACK,0);
ObjectSetInteger(0,name,OBJPROP_COLOR,type?BuyColor:SellColor);
if(profit!=0) ObjectSetString(0,name,OBJPROP_TEXT,"Profit: "+string(profit));
}
}
}
//--- apply on chart
ChartRedraw();
}
See also
HistoryOrderSelect(), HistoryDealSelect()
HistorySelectByPosition
Retrieves the history of deals and orders having the specified position identifier.
bool HistorySelectByPosition(
long position_id // position identifier - POSITION_IDENTIFIER
);
Parameters
position_id
[in] Position identifier that is set to every executed order and every deal.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
HistorySelectByPosition() creates in a mql5 program a list of orders and a list of deals with a
specified position identifier for further reference to the elements of the list using the appropriate
functions. To know the size of the list of deals, use function HistoryDealsTotal(), the size of the list
of orders in the history can be obtained using HistoryOrdersTotal(). To run through elements of the
orders list, use HistoryOrderGetTicket(), for elements of the deals list - HistoryDealGetTicket().
After using HistoryOrderSelect(), list of history orders available to the mql5 program is reset and
filled again with the found order, if search of an order by its ticket was successful. The same refers
to the list of deals available to the mql5 program - it is reset by function HistoryDealSelect() and is
filled out again if a deal was found successfully by the ticket number.
See also
HistorySelect(), HistoryOrderGetTicket(), Order Properties
HistoryOrderSelect
Selects an order from the history for further calling it through appropriate functions. It returns true if
the function has been successfully completed. Returns false if the function has failed. For more details
on error call GetLastError().
bool HistoryOrderSelect(
ulong ticket // Order ticket
);
Parameters
ticket
[in] Order ticket.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
HistoryOrderSelect() clears in a mql5-program the list of orders from a history, available for calls,
and copies to it a single order, if the execution of HistoryOrderSelect () has been completed
successfully. If you need to go through all deals selected by HistorySelect(), you should better use
HistoryOrderGetTicket().
See also
HistorySelect(), HistoryOrderGetTicket(), Order Properties
HistoryOrdersTotal
Returns the number of orders in the history. Prior to calling HistoryOrdersTotal(), first it is necessary
to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition()
function.
int HistoryOrdersTotal();
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrderSelect(), HistoryOrderGetTicket(), Order Properties
HistoryOrderGetTicket
Return the ticket of a corresponding order in the history. Prior to calling HistoryOrderGetTicket(),
first it is necessary to receive the history of deals and orders using the HistorySelect() or
HistorySelectByPosition() function.
ulong HistoryOrderGetTicket(
int index // Number in the list of orders
);
Parameters
index
[in] Number of the order in the list of orders.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
Example:
void OnStart()
{
datetime from=0;
datetime to=TimeCurrent();
//--- request the entire history
HistorySelect(from,to);
//--- variables for returning values from order properties
ulong ticket;
double open_price;
double initial_volume;
datetime time_setup;
datetime time_done;
string symbol;
string type;
long order_magic;
long positionID;
//--- number of current pending orders
uint total=HistoryOrdersTotal();
//--- go through orders in a loop
for(uint i=0;i<total;i++)
{
//--- return order ticket by its position in the list
if(ticket=HistoryOrderGetTicket(i))
{
//--- return order properties
open_price= HistoryOrderGetDouble(ticket,ORDER_PRICE_OPEN);
time_setup= HistoryOrderGetInteger(ticket,ORDER_TIME_SETUP);
time_done= HistoryOrderGetInteger(ticket,ORDER_TIME_DONE);
symbol= HistoryOrderGetString(ticket,ORDER_SYMBOL);
order_magic= HistoryOrderGetInteger(ticket,ORDER_MAGIC);
positionID = HistoryOrderGetInteger(ticket,ORDER_POSITION_ID);
initial_volume= HistoryOrderGetDouble(ticket,ORDER_VOLUME_INITIAL);
type=GetOrderType(HistoryOrderGetInteger(ticket,ORDER_TYPE));
//--- prepare and show information about the order
printf("#ticket %d %s %G %s at %G was set up at %s => done at %s, pos ID=%d",
ticket, // order ticket
type, // type
initial_volume, // placed volume
symbol, // symbol
open_price, // specified open price
TimeToString(time_setup),// time of order placing
TimeToString(time_done), // time of order execution or deletion
positionID // ID of a position , to which the deal of the order is in
);
}
}
//---
}
//+------------------------------------------------------------------+
//| returns the string name of the order type |
//+------------------------------------------------------------------+
string GetOrderType(long type)
{
string str_type="unknown operation";
switch(type)
{
case (ORDER_TYPE_BUY): return("buy");
case (ORDER_TYPE_SELL): return("sell");
case (ORDER_TYPE_BUY_LIMIT): return("buy limit");
case (ORDER_TYPE_SELL_LIMIT): return("sell limit");
case (ORDER_TYPE_BUY_STOP): return("buy stop");
case (ORDER_TYPE_SELL_STOP): return("sell stop");
case (ORDER_TYPE_BUY_STOP_LIMIT): return("buy stop limit");
case (ORDER_TYPE_SELL_STOP_LIMIT):return("sell stop limit");
}
return(str_type);
}
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
HistoryOrderGetDouble
Returns the requested order property. The order property must be of the double type. There are 2
variants of the function.
double HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_DOUBLE enumeration.
double_var
[out] Variable of the double type that accepts the value of the requested property.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
HistoryOrderGetInteger
Returns the requested property of an order. The order property must be of datetime, int type. There
are 2 variants of the function.
long HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_INTEGER enumeration.
long_var
[out] Variable of the long type that accepts the value of the requested property.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
HistoryOrderGetString
Returns the requested property of an order. The order property must be of the string type. There are
2 variants of the function.
string HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM_ORDER_PROPERTY_STRING enumeration.
string_var
[out] Variable of the string type.
Return Value
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
HistoryDealSelect
Selects a deal in the history for further calling it through appropriate functions. It returns true if the
function has been successfully completed. Returns false if the function has failed. For more details on
error call GetLastError().
bool HistoryDealSelect(
ulong ticket // Deal ticket
);
Parameters
ticket
[in] Deal ticket.
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
HistoryDealSelect() clears in a mql5-program the list of deals available for reference, and copies the
single deal, if the the execution of HistoryDealSelect() has been completed successfully. If you need
to go through all deals selected by the HistorySelect() function, you should better use
HistoryDealGetTicket().
See also
HistorySelect(), HistoryDealGetTicket(), Deal Properties
HistoryDealsTotal
Returns the number of deal in history. Prior to calling HistoryDealsTotal(), first it is necessary to
receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
int HistoryDealsTotal();
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealGetTicket(), Deal Properties
HistoryDealGetTicket
The function selects a deal for further processing and returns the deal ticket in history. Prior to calling
HistoryDealGetTicket(), first it is necessary to receive the history of deals and orders using the
HistorySelect() or HistorySelectByPosition() function.
ulong HistoryDealGetTicket(
int index // ticket deal
);
Parameters
index
[in] Number of a deal in the list of deals
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
Example:
void OnStart()
{
ulong deal_ticket; // deal ticket
ulong order_ticket; // ticket of the order the deal was executed on
datetime transaction_time; // time of a deal execution
long deal_type ; // type of a trade operation
long position_ID; // position ID
string deal_description; // operation description
double volume; // operation volume
string symbol; // symbol of the deal
//--- set the start and end date to request the history of deals
datetime from_date=0; // from the very beginning
datetime to_date=TimeCurrent();// till the current moment
//--- request the history of deals in the specified period
HistorySelect(from_date,to_date);
//--- total number in the list of deals
int deals=HistoryDealsTotal();
//--- now process each trade
for(int i=0;i<deals;i++)
{
deal_ticket= HistoryDealGetTicket(i);
volume= HistoryDealGetDouble(deal_ticket,DEAL_VOLUME);
transaction_time=(datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
order_ticket= HistoryDealGetInteger(deal_ticket,DEAL_ORDER);
deal_type= HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
symbol= HistoryDealGetString(deal_ticket,DEAL_SYMBOL);
position_ID= HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID);
deal_description= GetDealDescription(deal_type,volume,symbol,order_ticket,position_I
//--- perform fine formatting for the deal number
string print_index=StringFormat("% 3d",i);
//--- show information on the deal
Print(print_index+": deal #",deal_ticket," at ",transaction_time,deal_description);
}
}
//+------------------------------------------------------------------+
//| returns the string description of the operation |
//+------------------------------------------------------------------+
string GetDealDescription(long deal_type,double volume,string symbol,long ticket,long pos_ID)
{
string descr;
//---
switch(deal_type)
{
case DEAL_TYPE_BALANCE: return ("balance");
case DEAL_TYPE_CREDIT: return ("credit");
case DEAL_TYPE_CHARGE: return ("charge");
case DEAL_TYPE_CORRECTION: return ("correction");
case DEAL_TYPE_BUY: descr="buy"; break;
case DEAL_TYPE_SELL: descr="sell"; break;
}
descr=StringFormat("%s %G %s (order #%d, position ID %d)",
descr, // current description
volume, // deal volume
symbol, // deal symbol
ticket, // ticket of the order that caused the deal
pos_ID // ID of a position, in which the deal is included
);
return(descr);
//---
}
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
HistoryDealGetDouble
Returns the requested property of a deal. The deal property must be of the double type. There are 2
variants of the function.
double HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);
Parameters
ticket_number
[in] Deal ticket.
property_id
[in] Identifier of a deal property. The value can be one of the values of the
ENUM_DEAL_PROPERTY_DOUBLE enumeration.
double_var
[out] Variable of the double type that accepts the value of the requested property.
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
HistoryDealGetInteger
Returns the requested property of a deal. The deal property must be of the datetime, int type. There
are 2 variants of the function.
long HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);
Parameters
ticket_number
[in] Trade ticket.
property_id
[in] Identifier of the deal property. The value can be one of the values of the
ENUM_DEAL_PROPERTY_INTEGER enumeration.
long_var
[out] Variable of the long type that accepts the value of the requested property.
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
HistoryDealGetString
Returns the requested property of a deal. The deal property must be of the string type. There are 2
variants of the function.
string HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id // Property identifier
);
2. Returns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);
Parameters
ticket_number
[in] Deal ticket.
property_id
[in] Identifier of the deal property. The value can be one of the values of the
ENUM_DEAL_PROPERTY_STRING enumeration.
string_var
[out] Variable of the string type that accepts the value of the requested property.
Return Value
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order,
each position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
Global variables of the client terminal should not be mixed up with variables declared in the global
scope of the mql5 program.
Global variables are kept in the client terminal within 4 weeks since the last access, then they will be
deleted automatically. An access to a global variable is not only setting of a new value, but reading of
the global variable value, as well.
Global variables of the client terminal are accessible simultaneously from all mql5 programs launched
in the client terminal.
Function Action
GlobalVariableCheck
Checks the existence of a global variable with the specified name
bool GlobalVariableCheck(
string name // Global variable name
);
Parameters
name
[in] Global variable name.
Return Value
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
See also
GlobalVariableTime()
GlobalVariableTime
Returns the time when the global variable was last accessed.
datetime GlobalVariableTime(
string name // name
);
Parameters
name
[in] Name of the global variable.
Return Value
The function returns time of last accessing the specified global variable. Calling a variable to obtain
value is also considered as an access to it. In order to obtain error details, call the GetLastError()
function.
Note
Global variables exist in the client terminal during 4 weeks since they were called last. After that
they are automatic ally deleted.
See also
GlobalVariableCheck()
GlobalVariableDel
Deletes a global variable from the client terminal.
bool GlobalVariableDel(
string name // Global variable name
);
Parameters
name
[in] Global variable name.
Return Value
If successful, the function returns true, otherwise it returns false. To obtain an information about
the error it is necessary to call the function GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
GlobalVariableGet
Returns the value of an existing global variable of the client terminal. There are 2 variants of the
function.
double GlobalVariableGet(
string name // Global variable name
);
2. Returns true or false depending on the success of the function run. If successful, the global
variable of the client terminal is placed in a variable passed by reference in the second parameter.
bool GlobalVariableGet(
string name, // Global variable name
double& double_var // This variable will contain the value of the global variable
);
Parameters
name
[in] Global variable name.
double_var
[out] Target variable of the double type, which accepts the value stored in a the global variable of
the client terminal.
Return Value
The value of the existing global variable or 0 in case of an error. For more details about the error,
call GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
GlobalVariableName
Returns the name of a global variable by it's ordinal number.
string GlobalVariableName(
int index // Global variable number in the list of global variables
);
Parameters
index
[in] Sequence number in the list of global variables. It should be greater than or equal to 0 and
less than GlobalVariablesTotal().
Return Value
Global variable name by it's ordinal number in the list of global variables. For more details about the
error, call GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
GlobalVariableSet
Sets a new value for a global variable. If the variable does not exist, the system creates a new global
variable.
datetime GlobalVariableSet(
string name, // Global variable name
double value // Value to set
);
Parameters
name
[in] Global variable name.
value
[in] The new numerical value.
Return Value
If successful, the function returns the last modification time, otherwise 0. For more details about
the error, call GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
GlobalVariablesFlush
Forcibly saves contents of all global variables to a disk.
void GlobalVariablesFlush();
Return Value
No return value.
Note
The terminal writes all the global variables when the work is over, but data can be lost at a sudden
computer operation failure. This function allows independently controlling the process of saving
global variables in case of contingency.
GlobalVariableTemp
The function attempts to create a temporary global variable. If the variable doesn't exist, the system
creates a new temporary global variable.
bool GlobalVariableTemp(
string name // Global variable name
);
Parameters
name
[in] The name of a temporary global variable.
Return Value
If successful, the function returns true, otherwise - false. For details about the error, to call
GetLastError().
Note
Temporary global variables exist only while the client terminal is running; after the terminal
shutdown they are automatically deleted. Note that during the execution of GlobalVariablesFlush()
temporary global variables are not written to a disk.
After a temporary global variable has been created, it can be accessed and modified the same as
global variable of the client terminal.
GlobalVariableSetOnCondition
Sets the new value of the existing global variable if the current value equals to the third parameter
check_value. If there is no global variable, the function will generate an error
ERR_GLOBALVARIABLE_NOT_FOUND (4501) and return false.
bool GlobalVariableSetOnCondition(
string name, // Global variable name
double value, // New value for variable if condition is true
double check_value // Check value condition
);
Parameters
name
[in] The name of a global variable.
value
[in] New value.
check_value
[in] The value to check the current value of the global variable.
Return Value
If successful, the function returns true, otherwise it returns false. For details about the error call
GetLastError(). If the current value of the global variable is different from check_value, the
function returns false.
Note
Function provides atomic access to the global variable, so it can be used for providing of a mutex at
interaction of several Expert Advisors working simultaneously within one client terminal.
GlobalVariablesDeleteAll
Deletes global variables of the client terminal.
int GlobalVariablesDeleteAll(
string prefix_name=NULL, // All global variables with names beginning with the prefix
datetime limit_data=0 // All global variables that were changed before this date
);
Parameters
prefix_name=NULL
[in] Name prefix global variables to remove. If you specify a prefix NULL or empty string, then all
variables that meet the data criterion will be deleted.
limit_data=0
[in] Date to select global variables by the time of their last modification. The function removes
global variables, which were changed before this date. If the parameter is zero, then all variables
that meet the first criterion (prefix) are deleted.
Return Value
Note
If both options are equal to zero (prefix_name = NULL and limit_data = 0), then function deletes all
global variables of the terminal. If both parameters are specified, then it deletes global variables
corresponding to both parameters.
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
GlobalVariablesTotal
Returns the total number of global variables of the client terminal.
int GlobalVariablesTotal();
Return Value
Note
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted. Call of a global variable is not only setting a new value, but also reading the
value of the global variable.
File Functions
This is a group of functions for working with files.
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
There are two directories (with subdirectories) in which working files can be located:
terminal_path\MQL5\FILES\ (in the terminal menu select to view "File" - "Open the data directory");
the common folder for all the terminals installed on a computer - usually located in the directory C:
\Documents and Settings\All Users\Application Data\MetaQuotes\Terminal\Common\.
There is a program method to obtain names of these catalogs using the TerminalInfoString() function,
using the ENUM_TERMINAL_INFO_STRING enumerations:
Function Action
FolderCreate
If the file is opened for writing using FileOpen(), all subfolders specified in the path will be created if
there are no such ones.
FileFindFirst
The function starts the search of files in a directory in accordance with the specified filter.
long FileFindFirst(
string file_filter, // String - search filter
string& returned_filename, // Name of the file found
int common_flag // Defines the search
);
Parameters
file_filter
[in] Search filter. A subdirectory (or sequence of nested subdirectories) relative to the \Files
directory, in which files should be searched for, can be specified in the filter.
returned_filename
[out] The returned parameter, where, in case of success, the name of the first found file is
placed.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is
located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.
Return Value
Returns handle of the object searched, which should be used for further sorting of files by the
FileFindNext() function, or INVALID_HANDLE when there is no file corresponding to the filter (in the
particular case - when the directory is empty). After searching handle must be closed using the
FileFindClose() function.
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
Example:
void OnStart()
{
string filename;
//---
int found=FileFindFirst("*.*",filename);
if(found!=INVALID_HANDLE)
Print("FileFindFirst returned ",filename);
else
{
Print("Files not found!!! Continue search in Common");
found=FileFindFirst("*.*",filename,FILE_COMMON);
if(found!=INVALID_HANDLE)
Print("FileFindFirst in Common returned ",filename);
}
See also
FileFindNext, FileFindClose
FileFindNext
The function continues the search started by FileFindFirst().
bool FileFindNext(
long search_handle, // Search handle
string& returned_filename // Name of the file found
);
Parameters
search_handle
[in] Search handle, retrieved by FileFindFirst().
returned_filename
[out] The name of the next file or directory found.
Return Value
Example:
void OnStart()
{
string filename;
int i=0;
//---
int search=FileFindFirst("*.*",filename);
if(search!=INVALID_HANDLE)
{
Print("FileFindFirst returned ",filename);
while(FileFindNext(search,filename))
{
i++;
Print(i,":",filename);
}
FileFindClose(search);
}
else
Print("Files not found!!!");
}
See also
FileFindFirst, FileFindClose
FileFindClose
The function closes the search handle.
void FileFindClose(
long search_handle // Search handle
);
Parameters
search_handle
[in] Search handle, retrieved by FileFindFirst().
Return Value
No value returned.
Note
FileIsExist
Checks the existence of a file.
bool FileIsExist(
string file_name, // File name
int common_flag=0 // Search area
);
Parameters
file_name
[in] The name of the file being checked
common_flag=0
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is
located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
If common_flag = FILE_COMMON, then the function looks for the file in a shared folder for all client
terminals, otherwise the function looks for a file in a local folder (MQL5 \ Files or MQL5 \ Tester \
Files in the case of testing).
FileOpen
The function opens the file with the specified name and flag.
int FileOpen(
string file_name, // File name
int open_flags, // Combination of flags
short delimiter='\t' // Delimiter
uint codepage=CP_ACP // Code page
);
Parameters
file_name
[in] The name of the file can contain subfolders. If the file is opened for writing, these subfolders
will be created if there are no such ones.
open_flags
[in] combination of flags determining the operation mode for the file. The flags are defined as
follows:
FILE_READ file is opened for reading
FILE_WRITE file is opened for writing
FILE_BIN binary read-write mode (no conversion from a string and to a string)
FILE_CSV file of csv type (all recorded items are converted to the strings of unicode or ansi type,
and are separated by a delimiter)
FILE_TXT a simple text file (the same as csv, but the delimiter is not taken into account)
FILE_ANSI lines of ANSI type (single-byte symbols)
FILE_UNICODE lines of UNICODE type (double-byte characters)
FILE_SHARE_READ shared reading from several programs
FILE_SHARE_WRITE shared writing from several programs
FILE_COMMON location of the file in a shared folder for all client terminals
delimiter='\t'
[in] value to be used as a separator in txt or csv-file. If the csv-file delimiter is not specified, it
defaults to a tab. If the txt-file delimiter is not specified, then no separator is used. If the
separator is clearly set to 0, then no separator is used.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide appropriate constants.
Return Value
If a file has been opened successfully, the function returns the file handle, which is then used to
access the file data. In case of failure returns INVALID_HANDLE.
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
The file is opened in the folder of the client terminal in the subfolder MQL5\files (or
testing_agent_directory\MQL5\files in case of testing). If FILE_COMMON is specified among flags,
the file is opened in a shared folder for all MetaTrader 5 client terminals.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- incorrect file opening method
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
string filename=terminal_data_path+"\\MQL5\\Files\\"+"fractals.csv";
int filehandle=FileOpen(filename,FILE_WRITE|FILE_CSV);
if(filehandle<0)
{
Print("Failed to open the file by the absolute path ");
Print("Error code ",GetLastError());
}
See also
Use of a Codepage, FileFindFirst, FolderCreate, File opening flags
FileClose
Close the file previously opened by FileOpen().
void FileClose(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
No value returned.
FileCopy
The function copies the original file from a local or shared folder to another file.
bool FileCopy(
string src_filename, // Name of a source file
int common_flag, // Location
string dst_filename, // Name of the destination file
int mode_flags // Access mode
);
Parameters
src_filename
[in] File name to copy.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is
located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.
dst_filename
[in] Result file name.
mode_flags
[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or FILE_COMMON -
other flags are ignored. If the file already exists, and the FILE_REWRITE flag hasn't been
specified, then the file will not be rewritten, and the function will return false.
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
If the new file already exists, the copy will be made depending on the availability of the
FILE_REWRITE flag in the mode_flags parameter.
FileDelete
Deletes the specified file in a local folder of the client terminal.
bool FileDelete(
string file_name // File name to delete
int common_flag=0 // Location of the file to delete
);
Parameters
file_name
[in] File name.
common_flag=0
[in] Flag determining the file location. If common_flag = FILE_COMMON, then the file is located in
a shared folder for all client terminals. Otherwise, the file is located in a local folder.
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
Deletes the specified file from a local folder of the client terminal (MQL5\files or MQL5\tester\files
in case of testing). If common_flag = FILE_COMMON, then the function removes the file from the
shared folder for all client terminals.
FileMove
Moves a file from a local or shared folder to another folder.
bool FileMove(
string src_filename, // File name for the move operation
int common_flag, // Location
string dst_filename, // Name of the destination file
int mode_flags // Access mode
);
Parameters
src_filename
[in] File name to move/rename.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is
located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.
dst_filename
[in] File name after operation
mode_flags
[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or FILE_COMMON -
other flags are ignored. If the file already exists and the FILE_REWRITE flag isn't specified, the
file will not be rewritten, and the function will return false.
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
If the new file already exists, the copy will be made depending on the availability of the
FILE_REWRITE flag in the mode_flags parameter.
FileFlush
Writes to a disk all data remaining in the input/output file buffer.
void FileFlush(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
No value returned.
Note
Function FileFlush () must be called between the operations of reading from a file and write to a
file.
FileIsEnding
Defines the end of a file in the process of reading.
bool FileIsEnding(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The function returns true if the file end has been reached in the process of reading or moving of the
file pointer.
FileIsLineEnding
Defines the line end in a text file in the process of reading.
bool FileIsLineEnding(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Returns true if in the process of reading txt or csv-file reached the end of the line (the characters
CR-LF).
FileReadArray
Reads from a file of BIN type arrays of any type except string (may be an array of structures, not
containing strings, and dynamic arrays).
uint FileReadArray(
int file_handle // File handle
void array[], // Array to record
int start_item=0, // start array position to write
int items_count=WHOLE_ARRAY // count to read
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
array[]
[out] An array where the data will be loaded.
start_item=0
[in] Start position to write to the array.
items_count=WHOLE_ARRAY
[in] Number of elements to read. By default, reads the entire array (cnt=WHOLE_ARRAY).
Return Value
Note
String array can be read only from the file of TXT type. If necessary, the function tries to increase
the size of the array.
See also
Variables
FileReadBool
Reads from the file of CSV type string from the current position to a delimiter (or till the end of the
text line) and converts the read string to a bool type value.
bool FileReadBool(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Line read may be set to "true", "false" or the symbolic representation of integers "0" or "1". A
nonzero value is converted to a logical true. The function returns the converted value.
See also
Type bool
FileReadDatetime
Reads from the file of CSV type a string of one of the formats: "YYYY.MM.DD HH:MI:SS", "YYYY.MM.
DD" or "HH:MI:SS" - and converts it into a value of datetime type.
datetime FileReadDatetime(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
See also
Type datetime, StringToTime, TimeToString
FileReadDouble
Reads a double-precision floating point number (double) from the current position of the binary file.
double FileReadDouble(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Note
See also
Real types (double, float), StringToDouble, DoubleToString
FileReadFloat
Reads the single-precision floating point number (float) from the current position of the binary file.
float FileReadFloat(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Note
See also
Real types (double, float), FileReadDouble
FileReadInteger
The function reads int, short or char value from the current position of the file pointer depending on the
length specified in bytes.
int FileReadInteger(
int file_handle // File handle
int size=INT_VALUE // Size of an integer in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
size=INT_VALUE
[in] Number of bytes (up to 4 inclusive), that should be written. The corresponding constants are
provided: CHAR_VALUE = 1, SHORT_VALUE = 2 and INT_VALUE = 4, so the function can read the
whole value of char, short or int type.
Return Value
The value of int type. Since the int type value is returned, it can be converted to any integer,
signed or unsigned value. File pointer is moved by the number of bytes of the read integer type.
See also
IntegerToString, StringToInteger, Integer types
FileReadLong
The function reads an integer of long type (8 bytes) from the current position of the binary file.
long FileReadLong(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
See also
Integer types, FileReadInteger
FileReadNumber
The function reads from the CSV file a string from the current position till a separator (or till the end
of a text string) and converts the read string to a value of double type.
double FileReadNumber(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
FileReadString
The function reads from a string from the current position of a file pointer in a file.
string FileReadString(
int file_handle // File handle
int size=-1 // Length of the string
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
size=-1
[in] Number of characters to read.
Return Value
Note
When reading from a bin-file. the length of a string to read must be specified. When reading from a
txt-file the string length is not required, and the string will be read from the current position to the
line feed character "\r\n". When reading from a csv-file, the string length isn't required also, the
string will be read from the current position till the nearest delimiter or till the text string end
character.
If the file is opened with FILE_ANSI flag, then the line read is converted to Unicode.
See also
Type string, Data Conversion
FileReadStruct
The function reads contents into a structure passed as a parameter from a bin-file, starting with the
current position of the file pointer.
uint FileReadStruct(
int file_handle // File handle
any_simple_struct str_object, // target structure to read to
int size=-1 // structure size in bytes
);
Parameters
file_handle
[in] File descriptor of an open bin-file.
str_object
[out] The object of this structure. The structure should not contain strings, dynamic arrays or
virtual functions.
size=-1
[in] Number of bytes that should be read. If size is not specified or the indicated value is greater
than the size of the structure, the exact size of the specified structure is used.
Return Value
If successful the function returns the number of bytes read. File pointer is moved by the same
number of bytes.
See also
Structures and classes
FileSeek
The function moves the position of the file pointer by a specified number of bytes relative to the
specified position.
void FileSeek(
int file_handle // File handle
long offset, // In bytes
ENUM_FILE_POSITION origin // Position for reference
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
offset
[in] The shift in bytes (may take a negative value).
origin
[in] The starting point for the displacement. Can be one of values of ENUM_FILE_POSITION.
Return Value
No value returned.
Note
If the execution of the FileSeek() function results in a negative shift (going beyond the "level
boundary" of the file), the file pointer will be set to the file beginning.
If a position is set beyond the "right boundary" of the file (larger than the file size), the next writing
to the file will be performed not from the end of the file, but from the position set. In this case
indefinite values will be written for the previous file end and the position set.
FileSize
The function returns the file size in bytes.
ulong FileSize(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Note
FileTell
The file returns the current position of the file pointer of an open file.
ulong FileTell(
int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Current position of the file descriptor in bytes from the beginning of the file.
Note
FileWrite
The function is intended for writing of data into a CSV file, delimiter being inserted automatically
unless it is equal to 0. After writing into the file, the line end character "\r\n" will be added.
uint FileWrite(
int file_handle // File handle
... // List of recorded parameters
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
...
[in] The list of parameters separated by commas, to write to the file. The number of written
parameters can be up to 63.
Return Value
Note
Numbers will be converted into a text at output (see the Print() function). Data of the double type
are output with the accuracy of 16 digits after the decimal point, and the data can be displayed
either in traditional or in scientific format - depending on which format will be the most compact.
The data of the float type are shown with 5 digits after the decimal point. To output real numbers
with different precision or in a clearly specified format, use DoubleToString().
Numbers of the bool type are displayed as "true" or "false" strings. Numbers of the datetime type
are displayed as "YYYY.MM.DD HH:MI:SS".
See also
Comment, Print, StringFormat
FileWriteArray
The function writes arrays of any type except for string to a BIN file (can be an array of structures not
containing strings or dynamic arrays).
uint FileWriteArray(
int file_handle // File handle
void array[], // Array
int start_item=0, // Start index in the array
int items_count=WHOLE_ARRAY // Number of elements
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
array[]
[out] Array for recording.
start_item=0
[in] Initial index in the array (number of the first recorded element).
items_count=WHOLE_ARRAY
[in] Number of items to record (WHOLE_ARRAY means that records all items starting with the
number start_item until the end of the array).
Return Value
Note
String array can be recorded in a TXT file. In this case, strings are automatically ended by the line
end characters "\r\n". Depending on the file type ANSI or UNICODE, strings are either converted to
ansi-encoding or not.
See also
Variables
FileWriteDouble
The function writes the value of a double parameter to a file, starting from the current position of the
file pointer.
uint FileWriteDouble(
int file_handle // File handle
double dvalue // Value to write
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
dvalue
[in] The value of double type.
Return Value
If successful the function returns the number of bytes written (in this case sizeof(double)=8). The
file pointer is shifted by the same number of bytes.
See also
Real types (double, float)
FileWriteFloat
The function writes the value of the float parameter to a bin-file, starting from the current position of
the file pointer.
uint FileWriteFloat(
int file_handle // File handle
float fvalue // Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
fvalue
[in] The value of float type.
Return Value
If successful the function returns the number of bytes written (in this case sizeof(float)=4). The file
pointer is shifted by the same number of bytes.
See also
Real types (double, float), FileWriteDouble
FileWriteInteger
The function writes the value of the int parameter to a bin-file, starting from the current position of
the file pointer.
uint FileWriteInteger(
int file_handle // File handle
int ivalue, // Value to be written
int size=INT_VALUE // Size in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
ivalue
[in] Integer value.
size=INT_VALUE
[in] Number of bytes (up to 4 inclusive), that should be written. The corresponding constants are
provided: CHAR_VALUE=1, SHORT_VALUE=2 and INT_VALUE=4, so the function can write the
integer value of char, uchar, short, ushort, int, or uint type.
Return Value
If successful the function returns the number of bytes written. The file pointer is shifted by the
same number of bytes.
See also
IntegerToString, StringToInteger, Integer types
FileWriteLong
The function writes the value of the long-type parameter to a bin-file, starting from the current
position of the file pointer.
uint FileWriteLong(
int file_handle // File handle
long lvalue // Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
lvalue
[in] Value of type long.
Return Value
If successful the function returns the number of bytes written (in this case sizeof(long)=8). The file
pointer is shifted by the same number of bytes.
See also
Integer types, FileWriteInteger
FileWriteString
The function writes the value of a string-type parameter into a BIN or TXT file starting from the
current position of the file pointer. When writing to a TXT file: if there is a symbol in the string '\n'
(LF) without previous character '\r' (CR), then before '\n' the missing '\r' is added.
uint FileWriteString(
int file_handle // File handle
string svalue, // string to write
int size=-1 // number of symbols
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
svalue
[in] String.
size=-1
[in] The number of characters that you want to write. This option is needed for writing a string
into a BIN file. If the size is not specified, then the entire string without the trailer 0 is written. If
you specify a size smaller than the length of the string, then a part of the string without the trailer
0 is written. If you specify a size greater than the length of the string, the string is filled by the
appropriate number of zeros. For files of TXT type, this parameter is ignored and the string is
written entirely.
Return Value
If successful the function returns the number of bytes written. The file pointer is shifted by the
same number of bytes.
Note
Note that when writing to a file opened by the FILE_UNICODE flag (or without a flag FILE_ANSI),
then the number of bytes written will be twice as large as the number of string characters written.
When recording to a file opened with the FILE_ANSI flag, the number of bytes written will coincide
with the number of string characters written.
See also
Type string, StringFormat
FileWriteStruct
The function writes into a bin-file contents of a structure passed as a parameter, starting from the
current position of the file pointer.
uint FileWriteStruct(
int file_handle // File handle
any_simple_struct str_object&, // link to an object
int size=-1 // size to be written in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
str_object&
[in] Reference to the object of this structure. The structure should not contain strings, dynamic
arrays or virtual functions.
size=-1
[in] Number of bytes that you want to record. If size is not specified or the specified number of
bytes is greater than the size of the structure, the entire structure is written.
Return Value
If successful the function returns the number of bytes written. The file pointer is shifted by the
same number of bytes.
See also
Structures and classes
FolderCreate
The function creates a directory in the Files directory (depending on the value of common_flag).
bool FolderCreate(
string folder_name, // String with the name of the new folder
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory you want to create. Contains the full path to the folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag=FILE_COMMON, then the
directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder
(MQL5\files or MQL5\tester\files in case of testing).
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
FolderDelete
The function removes the specified directory. If the folder is not empty, then it can't be removed.
bool FolderDelete(
string folder_name, // String with the name of the folder to delete
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory you want to delete. Contains the full path to the folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag=FILE_COMMON, then the
directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder
(MQL5\files or MQL5\tester\files in the case of testing).
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
If the directory contains at least one file and/or subdirectory, then this directory can't be deleted, it
must be cleared first. FolderClean() is used to clear a folder of all its files or subfolders.
FolderClean
The function deletes all files in a specified folder.
bool FolderClean(
string folder_name, // String with the name of the deleted folder
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory where you want to delete all files. Contains the full path to the
folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag = FILE_COMMON, then the
directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder
(MQL5\files or MQL5\tester\files in case of testing).
Return Value
Note
For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file
operations are conducted using MQL5 means, cannot be outside the file sandbox.
This function should be used with caution, since all the files and all subdirectories are deleted
irretrievably.
Custom Indicators
This is the group functions used in the creation of custom indicators. These functions can't be used
when writing Expert Advisors and Scripts.
Function Action
Indicator properties can be set using the compiler directives or using functions. To better understand
this, it is recommended that you study indicator styles in examples.
All the necessary calculations of a custom indicator must be placed in the predetermined function
OnCalculate(). If you use a short form of the OnCalculate() function call, like
int OnCalculate (const int rates_total, const int prev_calculated, const int begin, const double& p
then the rates_total variable contains the value of the total number of elements of the price[] array,
passed as an input parameter for calculating indicator values.
Parameter prev_calculated is the result of the execution of OnCalculate() at the previous call; it allows
organizing a saving algorithm for calculating indicator values. For example, if the current value
rates_total = 1000, prev_calculated = 999, then perhaps it's enough to make calculations only for one
value of each indicator buffer.
If the information about the size of the input array price would have been unavailable, then it would
lead to the necessity to make calculations for 1000 values of each indicator buffer. At the first call of
OnCalculate() value prev_calculated = 0. If the price[] array has changed somehow, then in this case
prev_calculated is also equal to 0.
The begin parameter shows the number of initial values of the price array, which don't contain data
for calculation. For example, if values of Accelerator Oscillator (for which the first 37 values aren't
calculated) were used as an input parameter, then begin = 37. For example, let's consider a simple
indicator:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double Label1Buffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
//---
Print("begin = ",begin," prev_calculated = ",prev_calculated," rates_total = ",rates_total);
//--- return value of prev_calculated for next call
return(rates_total);
}
Drag it from the "Navigator" window to the window of the Accelerator Oscillator indicator and we
indicate that calculations will be made based on the values of the previous indicator:
As a result, the first call of OnCalculate() the value of prev_calculated will be equal to zero, and in
further calls it will be equal to the rates_total value (until the number of bars on the price chart
increases).
The value of the begin parameter will be exactly equal to the number of initial bars, for which the
values of the Accelerator indicator aren't calculated according to the logic of this indicator. If we look
at the source code of the custom indicator Accelerator.mq5, we'll see the following lines in the OnInit()
function:
1. set the number of initial values of an indicator, which shouldn't be used for calculations in another
custom indicator;
2. get information on the number of first values to be ignored when you call another custom indicator,
without going into the logic of its calculations.
indicator_applied_price No function, the property can Default price type used for the
be set only by the indicator calculation. It is
preprocessor directive. specified when necessary, only
if OnCalculate() of the first
type is used.
The property value can also be
set from the dialog of
indicator properties in the
"Parameters" tab - "Apply to".
It should be noted that numeration of levels and plots in preprocessor terms starts with one, while
numeration of the same properties at using functions starts with zero, i.e. the indicated value must
be by 1 less than that indicated for #property.
There are several directives, for which there are no corresponding functions:
Directive Description
The entire set of indicators can be derived from several base drawing styles, known as plotting.
Plotting denotes a way of displaying data, which the indicator calculates, stores and provides on
request. There are seven such basic plotting types:
1. A line
2. A section (segment)
3. Histogram
4. Arrow (symbol)
5. A painted area (filled channel)
6. Bars
7. Japanese candlesticks
Each plotting requires one to five arrays of the double type, in which indicator values are stored. For
the purpose of convenience, these arrays are associated with the indicator buffers. The number of
buffers in an indicator must be declared in advance using compiler directives, for example:
The number of buffers in the indicator is always greater than or equal to the number of plots in the
indicator.
Since each basic plotting type can have color variation or construction specifics, the actual number of
plotting types in the MQL5 is 18:
null values)
In each indicator, on its global level, you should declare one or more arrays of the double type, which
then must be used as an indicator buffer using the SetIndexBuffer() function. To draw indicator plots,
only the values of the indicator buffers are used, any other arrays cannot be used for this purpose. In
addition, buffer values are displayed in the Data Window.
An indicator buffer should be dynamic and does not require specification of the size – the size of the
array used as the indicator buffer, is set by the terminal execution subsystem automatically.
After the array is bound to the indicator buffer, the indexing direction is set by default like in ordinary
arrays, but you can use the ArraySetAsSeries() function to change the way of access to the array
elements. By default, the indicator buffer is used to store data used for plotting (INDICATOR_DATA).
If the calculation of indicator values requires holding intermediate calculations and storing the
additional values for each bar, then such an array can be declared as a calculation buffer during
binding (INDICATOR_CALCULATIONS). For the intermediate values, you can also use a regular array,
but in this case, the programmer has to manage the size of the array.
Some plots allow setting a color for each bar. To store the information about color, color buffers are
used (INDICATOR_COLOR_INDEX). The color is an integer type color, but all indicator buffers must be
of type double. Values of color and auxiliary (INDICATOR_CALCULATIONS) buffers cannot be obtained
by using CopyBuffer().
The number of indicator buffers must be specified using the compiler directive #property
indicator_buffers number_of_buffers:
Each plotting is based on one or more indicator buffers. So, for displaying simple candlesticks, four
values are required - Open, High, Low and Close prices. Accordingly, to display an indicator in the
form of candlesticks, it is necessary to declare 4 indicator buffers and 4 arrays of the double type for
them. For example:
Graphical plots automatically use indicator buffers in accordance with the plot number. Numbering of
plots starts with 1, numbering of buffers starts with zero. If the first plotting requires 4 indicator
buffers, then the first 4 indicator buffers will be used to draw it. These four buffers should be linked
with the appropriate arrays with correct indexing using the SetIndexBuffer() function.
The plotting candlesticks, the indicator will use just the first four buffers, because plotting of
"candlesticks" was announced under the first number.
Change the example, and add plotting of a simple line - DRAW_LINE. Now suppose that the line is
numbered 1, and the candlesticks are number 2. Количество буферов и количество
The order of the plots has changed, and now the line comes first, followed by Japanese candlesticks.
Therefore, the order of the buffers is appropriate - first we announce a buffer for the line with the
zero index, and then four buffers for the candlesticks.
The number of buffers and plots can be set only by using compiler directives, it is impossible to
change these properties dynamically using functions.
As can be seen in the table, the styles are divided into two groups. The first group includes styles in
whose name there is no word COLOR, we call these styles basic:
DRAW_LINE
DRAW_SECTION
DRAW_HISTOGRAM
DRAW_HISTOGRAM2
DRAW_ARROW
DRAW_ZIGZAG
DRAW_FILLING
DRAW_BARS
DRAW_CANDLES
In the second group, the style names contain the word COLOR, let's call them color versions:
DRAW_COLOR_LINE
DRAW_COLOR_SECTION
DRAW_COLOR_HISTOGRAM
DRAW_COLOR_HISTOGRAM2
DRAW_COLOR_ARROW
DRAW_COLOR_ZIGZAG
DRAW_COLOR_BARS
DRAW_COLOR_CANDLES
All color versions of styles differ from the basic ones in that they allow specifying a color for each part
of the plotting. The minimal part of plotting is a bar, so we can say that the color versions allow
setting the color on each bar.
Exceptions are styles DRAW_NONE and DRAW_FILLING, they do not have color versions.
To set the plotting color on each bar, an additional buffer for storing the color index has been added
to the color version. These indices indicate the number of a color in a special array, which contains a
predefined set of colors. The size of the array of colors is 64. This means that each color version of a
style allows painting a plot in 64 different colors.
The set and the number of colors in the special array of colors can be set via a compiler directive
#property indicator_color, where you can specified all the necessary colors separated by commas. For
example, such an entry in an indicator:
//--- Define 8 colors for coloring candlesticks (they are stored in the special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrYellow,clrMagenta,clrCyan,clrLime,clrOrange
It states that for plotting 1, 8 colors are set, which will be placed in a special array. Further in the
program we will not specify the color of the plotting, but only its index. If we want to set red color for
the bar number K, the color index value from an array should be set in the color buffer of the
indicator. The red color is specified first in the directive, it corresponds to the index number 0.
The set of colors is not given once and for all, it can be changed dynamically using PlotIndexSetInteger
(). Example:
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0, // The number of a graphical style
PLOT_LINE_COLOR, // Property identifier
plot_color_ind, // The index of the color, where we write the colo
color_array[i]); // A new color
For indicator plots, properties can be set by means of compiler directives and using the appropriate
functions. Read more information about this in Connection between Indicator Properties and Functions
. Dynamic change of indicator properties using special functions allows creating more flexible custom
indicators.
In many cases, according to the conditions of the algorithm, it is impossible to start calculating the
indicator values immediately with the current bar, since it is necessary to provide a minimum number
of previous bars available in history. For example, many types of smoothing imply using an array of
prices over the previous N bars, and on the basis of these values , the indicator value on the current
bar is calculated.
In such cases, either there is no way to calculate the indicator values for the first N bars, or these
values are not intended to be displayed on the chart and are only subsidiary for calculating further
values. To avoid plotting of the indicator on the first N bars of the history, set the N value to the
PLOT_DRAW_BEGIN property for the corresponding plot:
Here:
number_of_plot – a value from zero to indicator_plots-1 (numbering of plots starts with zero).
N - the number of first bars in the history, on which the indicator should not be displayed on the
chart.
DRAW_NONE
The DRAW_NONE style is designed for use in cases where it is necessary to calculate the values of a
buffer and show them in the Data Window, but plotting on the chart is not required. To set up the
accuracy use the expression IndicatorSetInteger(INDICATOR_DIGITS,num_chars) in the OnInit()
function:
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,InvisibleBuffer,INDICATOR_DATA);
//--- Set the accuracy of values to be displayed in the Data Window
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
return(0);
}
An example of the indicator that shows the number of the bar on which the mouse currently hovers, in
the Data Window. The numbering corresponds to the timeseries, meaning the current unfinished bar
has the zero index, and the oldest bar has the largest index.
Note that despite the fact that, for red color is set plotting №1, the indicator does not draw anything
on the chart.
//+------------------------------------------------------------------+
//| DRAW_NONE.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- plot Invisible
#property indicator_label1 "Bar Index"
#property indicator_type1 DRAW_NONE
#property indicator_style1 STYLE_SOLID
#property indicator_color1 clrRed
#property indicator_width1 1
//--- indicator buffers
double InvisibleBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,InvisibleBuffer,INDICATOR_DATA);
//--- Set the accuracy of values to be displayed in the Data Window
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static datetime lastbar=0;
//--- If this is the first calculation of the indicator
if(prev_calculated==0)
{
//--- Renumber the bars for the first time
CalcValues(rates_total,close);
//--- Remember the opening time of the current bar in lastbar
lastbar=(datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
}
else
{
//--- If a new bar has appeared, its open time differs from lastbar
if(lastbar!=SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE))
{
//--- Renumber the bars once again
CalcValues(rates_total,close);
//--- Update the opening time of the current bar in lastbar
lastbar=(datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Number the bars like in a timeseries |
//+------------------------------------------------------------------+
void CalcValues(int total,double const &array[])
{
//--- Set indexing of the indicator buffer like in a timeseries
ArraySetAsSeries(InvisibleBuffer,true);
//--- Fill in each bar with its number
for(int i=0;i<total;i++) InvisibleBuffer[i]=i;
}
DRAW_LINE
DRAW_LINE draws a line of the specified color by the values of the indicator buffer. The width, style
and color of the line can be set using the compiler directives and dynamically using the
PlotIndexSetInteger() function. Dynamic changes of the plotting properties allows "to enliven"
indicators, so that their appearance changes depending on the current situation.
An example of the indicator that draws a line using Close prices of bars. The line color, width and style
change randomly every N=5 ticks.
Note that initially for plot1 with DRAW_LINE the properties are set using the compiler directive
#property, and then in the OnCalculate() function these three properties are set randomly. The N
parameter is set in external parameters of the indicator for the possibility of manual configuration
(the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_LINE.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- свойства линии заданы с помощью лиректив компилятора
#property indicator_label1 "Line" // название построения для "Окна данных"
#property indicator_type1 DRAW_LINE // тип графического построения - линия
#property indicator_color1 clrRed // цвет линии
#property indicator_style1 STYLE_SOLID // стиль линии
#property indicator_width1 1 // толщина линии
//--- input parameter
input int N=5; // Number of ticks to change
//--- An indicator buffer for the plot
double LineBuffer[];
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
//--- Initializing the generator of pseudo-random numbers
MathSrand(GetTickCount());
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a critical number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| изменяет внешний вид отображаемой линии в индикаторе |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the color of the line
//--- получим случайное число
int number=MathRand();
//--- The divisor is equal to the size of the colors[] array
int size=ArraySize(colors);
//--- Get the index to select a new color as the remainder of integer division
int color_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,colors[color_index]);
//--- Write the line color
comm=comm+(string)colors[color_index];
size=ArraySize(styles);
//--- Get the index to select a new style as the remainder of integer division
int style_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_STYLE,styles[style_index]);
//--- Write the line style
comm=EnumToString(styles[style_index])+", "+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
DRAW_SECTION
DRAW_SECTION draws sections of the specified color by the values of the indicator buffer. The width,
color and style of the line can be specified like for the DRAW_LINE style - using compiler directives or
dynamically using the PlotIndexSetInteger() function. Dynamic changes of the plotting properties
allows "to enliven" indicators, so that their appearance changes depending on the current situation.
Sections are drawn from one non-null value to another non-null value of the indicator buffer, empty
values are ignored. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property: For example, if the indicator should be drawn as a sequence of sections
on non-zero values, then you need to set the zero value as an empty one:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to the elements
that should not be plotted.
An example of the indicator that draws sections between the High and Low prices. The color, width
and style of all sections change randomly every N ticks.
Note that initially for plot1 with DRAW_SECTION the properties are set using the compiler directive
#property, and then in the OnCalculate() function these three properties are set randomly. The N
parameter is set in external parameters of the indicator for the possibility of manual configuration
(the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_SECTION.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- plot Section
#property indicator_label1 "Section"
#property indicator_type1 DRAW_SECTION
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameter
input int bars=5; // The length of sections in bars
input int N=5; // The number of ticks to change the style of sections
//--- An indicator buffer for the plot
double SectionBuffer[];
//--- An auxiliary variable to calculate ends of sections
int divider;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,SectionBuffer,INDICATOR_DATA);
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- Check the indicator parameter
if(bars<=0)
{
PrintFormat("Invalid value of parameter bar=%d",bars);
return(-1);
}
else divider=2*bars;
//---+
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a critical number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- The number of the bar from which the calculation of indicator values starts
int start=0;
//--- If the indicator has been calculated before, then set start on the previous bar
if(prev_calculated>0) start=prev_calculated-1;
//--- Here are all the calculations of the indicator values
for(int i=start;i<rates_total;i++)
{
//--- Get a remainder of the division of the bar number by 2*bars
int rest=i%divider;
//--- If the bar number is divisible by 2*bars
if(rest==0)
{
//--- Set the end of the section at the High price of this bar
SectionBuffer[i]=high[i];
}
//---If the remainder of the division is equal to bars,
else
{
//--- Set the end of the section at the High price of this bar
if(rest==bars) SectionBuffer[i]=low[i];
//--- If nothing happened, ignore the bar - set 0
else SectionBuffer[i]=0;
}
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the appearance of sections in the indicator |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block of line color change
int number=MathRand(); // Get a random number
//--- The divisor is equal to the size of the colors[] array
int size=ArraySize(colors);
//--- Get the index to select a new color as the remainder of integer division
int color_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,colors[color_index]);
//--- Write the line color
comm=comm+"\r\n"+(string)colors[color_index];
DRAW_HISTOGRAM
The DRAW_HISTOGRAM style draws a histogram as a sequence of columns of a specified color from
zero to a specified value. Values are taken from the indicator buffer. The width, color and style of the
column can be specified like for the DRAW_LINE style - using compiler directives or dynamically using
the PlotIndexSetInteger() function. Dynamic changes of the plotting properties allows changing the
look of the histogram based on the current situation.
Since a column from the zero level is drawn on each bar, DRAW_HISTOGRAM should better be used in
a separate chart window. Most often this type of plotting is used to create indicators of the oscillator
type, for example, Bears Power or OsMA. For the empty non-displayable values the zero value should
be specified.
An example of the indicator that draws a sinusoid of a specified color based on the MathSin() function
. The color, width and style of all histogram columns change randomly each N ticks. The bars
parameter specifies the period of the sinusoid, that is after the specified number of bars the sinusoid
will repeat the cycle.
Note that initially for plot1 with DRAW_HISTOGRAM the properties are set using the compiler
directive #property, and then in the OnCalculate() function these three properties are set randomly.
The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_HISTOGRAM.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//--- plot Histogram
#property indicator_label1 "Histogram"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=30; // The period of a sinusoid in bars
input int N=5; // The number of ticks to change the histogram
//--- indicator buffers
double HistogramBuffer[];
//--- A factor to get the 2Pi angle in radians, when multiplied by the bars parameter
double multiplier;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,HistogramBuffer,INDICATOR_DATA);
//--- Calculate the multiplier
if(bars>1)multiplier=2.*M_PI/bars;
else
{
PrintFormat("Set the value of bars=%d greater than 1",bars);
//--- Early termination of the indicator
return(-1);
}
//---
return(0);
}
//+------------------------------------------------------------------+
//--- Get the index to select a new color as the remainder of integer division
int color_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,colors[color_index]);
//--- Write the line color
comm=comm+"\r\n"+(string)colors[color_index];
DRAW_HISTOGRAM2
The DRAW_HISTOGRAM2 style draws a histogram of a specified color – vertical segments using the
values of two indicator buffers. The width, color and style of the segments can be specified like for
the DRAW_LINE style - using compiler directives or dynamically using the PlotIndexSetInteger()
function. Dynamic changes of the plotting properties allows changing the look of the histogram based
on the current situation.
The DRAW_HISTOGRAM2 style can be used in a separate subwindow of a chart and in its main
window. For null values nothing is drawn, all the values in the indicator buffers need to be set
explicitly. Buffers are not initialized with a zero value.
An example of the indicator that plots a vertical segment of the specified color and width between the
Open and Close prices of each bar. The color, width and style of all histogram columns change
randomly each N ticks. During the start of the indicator, in the OnInit() function, the number of the
weekday for which the histogram will not be drawn - invisible_day - is set randomly. For this purpose
an empty value is set PLOT_EMPTY_VALUE=0:
Note that initially for plot1 with DRAW_HISTOGRAM2 the properties are set using the compiler
directive #property, and then in the OnCalculate() function these three properties are set randomly.
The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_HISTOGRAM2.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot Histogram_2
#property indicator_label1 "Histogram_2"
#property indicator_type1 DRAW_HISTOGRAM2
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int N=5; // The number of ticks to change the histogram
//--- indicator buffers
double Histogram_2Buffer1[];
double Histogram_2Buffer2[];
//--- The day of the week for which the indicator is not plotted
int invisible_day;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Histogram_2Buffer1,INDICATOR_DATA);
SetIndexBuffer(1,Histogram_2Buffer2,INDICATOR_DATA);
//--- Set an empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- Get a random number from 0 to 5
invisible_day=MathRand()%6;
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
DRAW_ARROW
The DRAW_ARROW style draws arrows of the specified color (symbols of the set Wingdings) based on
the value of the indicator buffer. The width and color of the symbols can be specified like for the
DRAW_LINE style - using compiler directives or dynamically using the PlotIndexSetInteger() function.
Dynamic changes of the plotting properties allows changing the look of an indicator based on the
current situation.
//--- Define the symbol code from the Wingdings font to draw in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
Each arrow is actually a symbol that has the height and the anchor point, and can cover some
important information on a chart (for example, the closing price at the bar). Therefore, we can
additionally specify the vertical shift in pixels, which does not depend on the scale of the chart. The
arrows will be shifted down by the specified number of pixels, although the values of the indicator will
remain the same:
A negative value of PLOT_ARROW_SHIFT means the shift of arrows upwards, a positive values shifts
the arrow down.
The DRAW_ARROW style can be used in a separate subwindow of a chart and in its main window. Null
values are not drawn and do not appear in the "Data Window", all the values in the indicator buffers
should be set explicitly. Buffers are not initialized with a zero value.
An example of the indicator, which draws arrows on each bar with the the close price higher than the
close price of the previous bar. The color, width, shift and symbol code of all arrows are changed
randomly every N ticks.
In the example, for plot1 with the DRAW_ARROW style, the properties, color and size are specified
using the compiler directive #property, and then in the OnCalculate() function the properties are set
randomly. The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_ARROW.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- plot Arrows
#property indicator_label1 "Arrows"
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrGreen
#property indicator_width1 1
//--- input parameters
PlotIndexSetInteger(0,PLOT_ARROW,code+code_add);
//--- Write the symbol code PLOT_ARROW
comm="\r\n"+"PLOT_ARROW="+IntegerToString(code+code_add)+comm;
DRAW_ZIGZAG
The DRAW_ZIGZAG style draws segments of a specified color based on the values of two indicator
buffers. This style is very similar to DRAW_SECTION, but unlike the latter, it allows drawing vertical
segments within one bar, if values of both indicator buffers are set for this bar. The segments are
plotted from a value in the first buffer to a value in the second indicator buffer. None of the buffers
can contain only null values, since in this case nothing is plotted.
The width, color and style of the line can be specified like for the DRAW_SECTION style - using
compiler directives or dynamically using the <li7>PlotIndexSetInteger()</li7><t8> function. Dynamic
changes of the plotting properties allows "to enliven" indicators, so that their appearance changes
depending on the current situation.
Sections are drawn from a non-null value of one buffer to a non-null value of another indicator buffer.
To specify what value should be considered as "empty", set this value in the PLOT_EMPTY_VALUE
property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
An example of the indicator that plots a saw based on the High and Low prices. The color, width and
style of the zigzag lines change randomly every N ticks.
Note that initially for plot1 with DRAW_ZIGZAG the properties are set using the compiler directive
#property, and then in the OnCalculate() function these properties are set randomly. The N parameter
is set in external parameters of the indicator for the possibility of manual configuration (the
Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_ZIGZAG.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot ZigZag
#property indicator_label1 "ZigZag"
#property indicator_type1 DRAW_ZIGZAG
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int N=5; // Number of ticks to change
//--- indicator buffers
double ZigZagBuffer1[];
double ZigZagBuffer2[];
//--- The day of the week for which the indicator is not plotted
int invisible_day;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding arrays and indicator buffers
SetIndexBuffer(0,ZigZagBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,ZigZagBuffer2,INDICATOR_DATA);
//--- Get a random value from 0 to 6, for this day the indicator is not plotted
invisible_day=MathRand()%6;
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetString(0,PLOT_LABEL,"ZigZag1;ZigZag2");
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a sufficient number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- The structure of time is required to get the weekday of each bar
MqlDateTime dt;
}
//--- If the day of the week is ok, fill in the buffers
else
{
//--- If the bar number if even
if(i%2==0)
{
//--- Write High in the 1st buffer and Low in the 2nd one
ZigZagBuffer1[i]=high[i];
ZigZagBuffer2[i]=low[i];
}
//--- The bar number is odd
else
{
//--- Fill in the bar in a reverse order
ZigZagBuffer1[i]=low[i];
ZigZagBuffer2[i]=high[i];
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the appearance of the zigzag segments |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the ZigZag properties
string comm="";
//--- A block for changing the color of the ZigZag
int number=MathRand(); // Get a random number
//--- The divisor is equal to the size of the colors[] array
int size=ArraySize(colors);
//--- Get the index to select a new color as the remainder of integer division
int color_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,colors[color_index]);
//--- Write the line color
comm=comm+"\r\n"+(string)colors[color_index];
comm=comm+"\r\nWidth="+IntegerToString(width);
DRAW_FILLING
The DRAW_FILLING style plots a colored area between the values of two indicator buffers. In fact, this
style draws two lines and fills the space between them with one of two specified colors. Is is used for
creating indicators that draw channels. None of the buffers can contain only null values, since in this
case nothing is plotted.
the first color is used for the areas where values in the first buffer are greater than the values in
the second indicator buffer;
the second color is used for the areas where values in the second buffer are greater than the values
in the first indicator buffer.
The fill color can be set using the compiler directives or dynamically using the PlotIndexSetInteger()
function. Dynamic changes of the plotting properties allows "to enliven" indicators, so that their
appearance changes depending on the current situation.
The indicator is drawn only to those bars, for which non-empty values of both indicator buffers are
specified. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
An example of the indicator that draws a channel between two MAs with different averaging periods in
a separate window. The change of the colors at the crossing of moving averages visually shows the
change of the upward and downward trends. The colors change randomly every N ticks. The N
parameter is set in external parameters of the indicator for the possibility of manual configuration
(the Parameters tab in the indicator's Properties window).
Note that initially for plot1 with DRAW_FILLING the properties are set using the compiler directive
#property, and then in the OnCalculate() function new colors are set randomly.
//+------------------------------------------------------------------+
//| DRAW_FILLING.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot Intersection
#property indicator_label1 "Intersection"
#property indicator_type1 DRAW_FILLING
#property indicator_color1 clrRed,clrBlue
#property indicator_width1 1
//--- input parameters
input int Fast=13; // The period of a fast MA
input int Slow=21; // The period of a slow MA
input int shift=1; // A shift of MAs towards the future (positive)
//--- Make the first calculation of the indicator, or data has changed and requires a complete reca
if(prev_calculated==0)
{
//--- Copy all the values of the indicators to the appropriate buffers
int copied1=CopyBuffer(fast_handle,0,0,rates_total,IntersectionBuffer1);
int copied2=CopyBuffer(slow_handle,0,0,rates_total,IntersectionBuffer2);
}
else // Fill only those data that are updated
{
//--- Get the difference in bars between the current and previous start of OnCalculate()
int to_copy=rates_total-prev_calculated;
//--- If there is no difference, we still copy one value - on the zero bar
if(to_copy==0) to_copy=1;
//--- copy to_copy values to the very end of indicator buffers
int copied1=CopyBuffer(fast_handle,0,0,to_copy,IntersectionBuffer1);
int copied2=CopyBuffer(slow_handle,0,0,to_copy,IntersectionBuffer2);
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the colors of the channel filling |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the color of the line
int number=MathRand(); // Get a random number
//--- The divisor is equal to the size of the colors[] array
int size=ArraySize(colors);
//--- Get the index to select a new color as the remainder of integer division
int color_index1=number%size;
//--- Set the first color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,colors[color_index1]);
//--- Write the first color
comm=comm+"\r\nColor1 "+(string)colors[color_index1];
//--- Get the index to select a new color as the remainder of integer division
number=MathRand(); // Get a random number
int color_index2=number%size;
//--- Set the second color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,colors[color_index2]);
//--- Write the second color
comm=comm+"\r\nColor2 "+(string)colors[color_index2];
DRAW_BARS
The DRAW_BARS style draws bars on the values of four indicator buffers, which contain the Open,
High, Low and Close prices. It used for creating custom indicators as bars, including those in a
separate subwindow of a chart and on other financial instruments.
The color of bars can be set using the compiler directives or dynamically using the PlotIndexSetInteger
() function. Dynamic changes of the plotting properties allows "to enliven" indicators, so that their
appearance changes depending on the current situation.
The indicator is drawn only to those bars, for which non-empty values of all four indicator buffers are
set. To specify what value should be considered as "empty", set this value in the PLOT_EMPTY_VALUE
property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
The number of required buffers for plotting DRAW_BARS is 4. All buffers for the plotting should go one
after the other in the given order: Open, High, Low and Close. None of the buffers can contain only
null values, since in this case nothing is plotted.
An example of the indicator that draws bars on a selected financial instrument in a separate window.
The color of bars changes randomly every N ticks. The N parameter is set in external parameters of
the indicator for the possibility of manual configuration (the Parameters tab in the indicator's
Properties window).
Please note that for plot1 with the DRAW_BARS style, the color is set using the compiler directive
#property, and then in the OnCalculate() function the color is set randomly from an earlier prepared
list.
//+------------------------------------------------------------------+
//| DRAW_BARS.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots 1
//--- plot Bars
#property indicator_label1 "Bars"
#property indicator_type1 DRAW_BARS
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int N=5; // The number of ticks to change the type
input int bars=500; // The number of bars to show
input bool messages=false; // Show messages in the "Expert Advisors" log
//--- Indicator buffers
double BarsBuffer1[];
double BarsBuffer2[];
double BarsBuffer3[];
double BarsBuffer4[];
//--- Symbol name
string symbol;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen,clrPurple,clrBrown,clrIndianRed};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- If bars is very small - complete the work ahead of time
if(bars<50)
{
Comment("Please specify a larger number of bars! The operation of the indicator has been term
return(-1);
}
//--- indicator buffers mapping
SetIndexBuffer(0,BarsBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,BarsBuffer2,INDICATOR_DATA);
SetIndexBuffer(2,BarsBuffer3,INDICATOR_DATA);
SetIndexBuffer(3,BarsBuffer4,INDICATOR_DATA);
//--- The name of the symbol, for which the bars are drawn
symbol=_Symbol;
//--- Set the display of the symbol
PlotIndexSetString(0,PLOT_LABEL,symbol+" Open;"+symbol+" High;"+symbol+" Low;"+symbol+" Close");
IndicatorSetString(INDICATOR_SHORTNAME,"DRAW_BARS("+symbol+")");
//--- Null value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a sufficient number of ticks has been accumulated
if(ticks>=N)
{
//--- Select a new symbol from the Market watch window
symbol=GetRandomSymbolName();
//--- Change the line properties
ChangeLineAppearance();
int tries=0;
//--- Make 5 attempts to fill in the buffers with the prices from symbol
while(!CopyFromSymbolToBuffers(symbol,rates_total) && tries<5)
{
//--- A counter of calls of the CopyFromSymbolToBuffers() function
tries++;
}
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Fill in the indicator buffers with prices |
//+------------------------------------------------------------------+
bool CopyFromSymbolToBuffers(string name,int total)
{
//--- In the rates[] array, we will copy Open, High, Low and Close
MqlRates rates[];
//--- The counter of attempts
int attempts=0;
//--- How much has been copied
int copied=0;
//--- Make 25 attempts to get a timeseries on the desired symbol
while(attempts<25 && (copied=CopyRates(name,_Period,0,bars,rates))<0)
{
Sleep(100);
attempts++;
if(messages) PrintFormat("%s CopyRates(%s) attempts=%d",__FUNCTION__,name,attempts);
}
//--- If failed to copy a sufficient number of bars
if(copied!=bars)
{
//--- Form a message string
string comm=StringFormat("For the symbol %s, managed to receive only %d bars of %d requested
name,
copied,
bars
);
//--- Show a message in a comment in the main chart window
Comment(comm);
//--- Show the message
if(messages) Print(comm);
return(false);
}
else
{
//--- Set the display of the symbol
PlotIndexSetString(0,PLOT_LABEL,name+" Open;"+name+" High;"+name+" Low;"+name+" Close");
IndicatorSetString(INDICATOR_SHORTNAME,"DRAW_BARS("+name+")");
}
//--- Initialize buffers with empty values
ArrayInitialize(BarsBuffer1,0.0);
ArrayInitialize(BarsBuffer2,0.0);
ArrayInitialize(BarsBuffer3,0.0);
ArrayInitialize(BarsBuffer4,0.0);
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,width);
//--- Write the line width
comm=comm+"\r\nWidth="+IntegerToString(width);
DRAW_CANDLES
The DRAW_CANDLES style draws candlesticks on the values of four indicator buffers, which contain
the Open, High, Low and Close prices. It used for creating custom indicators as a sequence of
candlesticks, including those in a separate subwindow of a chart and on other financial instruments.
The color of candlesticks can be set using the compiler directives or dynamically using the
PlotIndexSetInteger() function. Dynamic changes of the plotting properties allows "to enliven"
indicators, so that their appearance changes depending on the current situation.
The indicator is drawn only to those bars, for which non-empty values of all four indicator buffers are
set. To specify what value should be considered as "empty", set this value in the PLOT_EMPTY_VALUE
property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
The number of required buffers for plotting DRAW_CANDLES is 4. All buffers for the plotting should go
one after the other in the given order: Open, High, Low and Close. None of the buffers can contain
only null values, since in this case nothing is plotted.
An example of the indicator that draws candlesticks for a selected financial instrument in a separate
window. The color of candlesticks changes randomly every N ticks. The N parameter is set in external
parameters of the indicator for the possibility of manual configuration (the Parameters tab in the
indicator's Properties window).
Please note that for plot1, the color is set using the compiler directive #property, and then in the
OnCalculate() function the color is set randomly from an earlier prepared list.
//+------------------------------------------------------------------+
//| DRAW_CANDLES.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots 1
//--- plot Bars
#property indicator_label1 "DRAW_CANDLES1"
#property indicator_type1 DRAW_CANDLES
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
}
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Fills in the specified candlestick |
//+------------------------------------------------------------------+
bool CopyFromSymbolToBuffers(string name,
int total,
int plot_index,
double &buff1[],
double &buff2[],
double &buff3[],
double &buff4[]
)
{
//--- In the rates[] array, we will copy Open, High, Low and Close
MqlRates rates[];
//--- The counter of attempts
int attempts=0;
//--- How much has been copied
int copied=0;
//--- Make 25 attempts to get a timeseries on the desired symbol
while(attempts<25 && (copied=CopyRates(name,_Period,0,bars,rates))<0)
{
Sleep(100);
attempts++;
if(messages) PrintFormat("%s CopyRates(%s) attempts=%d",__FUNCTION__,name,attempts);
}
//--- If failed to copy a sufficient number of bars
if(copied!=bars)
{
//--- Form a message string
string comm=StringFormat("For the symbol %s, managed to receive only %d bars of %d requested
name,
copied,
bars
);
//--- Show a message in a comment in the main chart window
Comment(comm);
//--- Show the message
if(messages) Print(comm);
return(false);
}
else
{
//--- Set the display of the symbol
PlotIndexSetString(plot_index,PLOT_LABEL,name+" Open;"+name+" High;"+name+" Low;"+name+" Clos
}
//--- Initialize buffers with empty values
ArrayInitialize(buff1,0.0);
ArrayInitialize(buff2,0.0);
ArrayInitialize(buff3,0.0);
ArrayInitialize(buff4,0.0);
//--- On each tick copy prices to buffers
for(int i=0;i<copied;i++)
{
//--- Calculate the appropriate index for the buffers
int buffer_index=total-copied+i;
//--- Write the prices to the buffers
buff1[buffer_index]=rates[i].open;
buff2[buffer_index]=rates[i].high;
buff3[buffer_index]=rates[i].low;
buff4[buffer_index]=rates[i].close;
}
return(true);
}
//+------------------------------------------------------------------+
//| Randomly returns a symbol from the Market Watch |
//+------------------------------------------------------------------+
string GetRandomSymbolName()
{
//--- The number of symbols shown in the Market watch window
int symbols=SymbolsTotal(true);
//--- The position of a symbol in the list - a random number from 0 to symbols
int number=MathRand()%symbols;
//--- Return the name of a symbol at the specified position
return SymbolName(number,true);
}
//+------------------------------------------------------------------+
//| Changes the appearance of bars |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the bar properties
string comm="";
//--- A block for changing the color of bars
int number=MathRand(); // Get a random number
//--- The divisor is equal to the size of the colors[] array
int size=ArraySize(colors);
//--- Get the index to select a new color as the remainder of integer division
int color_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_COLOR,colors[color_index]);
//--- Write the color
comm=comm+"\r\n"+(string)colors[color_index];
//--- Write the symbol name
comm="\r\n"+symbol+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
DRAW_COLOR_LINE
The DRAW_COLOR_LINE value is a colored variant of the DRAW_LINE style; it also draws a line using
the values of the indicator buffer. But this style, like all color styles with the word COLOR in their title
has an additional special indicator buffer that stores the color index (number) from a specially set
array of colors. Thus, the color of each line segment can be defined by specifying the color index of
the index to draw the line at this bar.
The width, style and colors of lines can be set using the compiler directives and dynamically using the
PlotIndexSetInteger() function. Dynamic changes of the plotting properties allows "to enliven"
indicators, so that their appearance changes depending on the current situation.
one buffer to store the indicator values used for drawing a line;
one buffer to store the index of the color of the line on each bar.
Colors can be specified by the compiler directive #property indicator_color1 separated by a comma.
The number of colors cannot exceed 64.
//--- Define 5 colors for coloring each bar (they are stored in the special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrOrange,clrDeepPink // (Up to 64 colors can b
An example of the indicator that draws a line using Close prices of bars. The line width and style
change randomly every N=5 ticks.
The colors of the line segments also change randomly in the custom function ChangeColors().
//+------------------------------------------------------------------+
//| Changes the color of line segments |
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
The example shows the feature of the "color" versions of indicators - to change the color of a line
segment, you do not need to change values in the ColorLineColors[] buffer (which contains the color
indexes). All you need to do is set new colors in a special array. This allows you to quickly change the
color once for the entire plotting, changing only a small array of colors using the PlotIndexSetInteger()
function.
Note that initially for plot1 with DRAW_COLOR_LINE the properties are set using the compiler
directive #property, and then in the OnCalculate() function these three properties are set randomly.
The N and Length (the length of color segments in bars) parameters are set in external parameters of
the indicator for the possibility of manual configuration (the Parameters tab in the indicator's
Properties window).
//+------------------------------------------------------------------+
//| DRAW_COLOR_LINE.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot ColorLine
#property indicator_label1 "ColorLine"
#property indicator_type1 DRAW_COLOR_LINE
//--- Define 5 colors for coloring each bar (they are stored in the special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrOrange,clrDeepPink // (Up to 64 colors can b
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int N=5; //Number of ticks to change
input int Length=20; // The length of each color part in bars
int line_colors=5; // The number of set colors is 5 - see #property indicator_color1
//--- A buffer for plotting
double ColorLineBuffer[];
//--- A buffer for storing the line color on each bar
double ColorLineColors[];
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the color of line segments |
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
//--- Get an index in the col[] array as a remainder of the integer devision
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0, // The number of a graphical style
PLOT_LINE_COLOR, // Property identifier
plot_color_ind, // The index of the color, where we write the colo
cols[i]); // A new color
//--- Write the colors
comm=comm+StringFormat("LineColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],true
ChartSetString(0,CHART_COMMENT,comm);
}
//---
}
//+------------------------------------------------------------------+
//| Changes the appearance of a displayed line in the indicator |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the width of the line
int number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5; // The width is set from 0 to 4
//--- Set the color as the PLOT_LINE_WIDTH property
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,width);
//--- Write the line width
comm=comm+" Width="+IntegerToString(width);
DRAW_COLOR_SECTION
The DRAW_COLOR_SECTION style is a color version of DRAW_SECTION, but unlike the latter, it allows
drawing sections of different colors. The DRAW_COLOR_SECTION style, like all color styles with the
word COLOR in their title, contains an additional special indicator buffer that stores the color index
(number) from a specially set array of colors. Thus, the color of each sections can be defined by
specifying the color index of the index of the bar that corresponds to the section end.
The width, color and style of the sections can be specified like for the DRAW_SECTION style - using
compiler directives or dynamically using the PlotIndexSetInteger() function. Dynamic changes of the
plotting properties allows "to enliven" indicators, so that their appearance changes depending on the
current situation.
Sections are drawn from one non-null value to another non-null value of the indicator buffer, empty
values are ignored. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property: For example, if the indicator should be drawn as a sequence of sections
on non-zero values, then you need to set the zero value as an empty one:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to the elements
that should not be plotted.
one buffer to store the indicator values used for drawing a line;
one buffer to store the color index, which is used to draw the section (it makes sense to set only
non-empty values).
Colors can be specified by the compiler directive #property indicator_color1 separated by a comma.
The number of colors cannot exceed 64.
An example of the indicator that draws colored sections each 5 bars long, using the High price values.
The color, width and style of sections change randomly every N ticks.
Note that initially for plot1 with DRAW_COLOR_SECTION 8 colors are set using the compiler directive
#property. Then in the OnCalculate() function, colors are set randomly from the array of colors colors
[].
The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_COLOR_SECTION.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot ColorSection
#property indicator_label1 "ColorSection"
#property indicator_type1 DRAW_COLOR_SECTION
//--- Define 8 colors for coloring sections (they are stored in a special array)
#property indicator_color1 clrRed,clrGold,clrMediumBlue,clrLime,clrMagenta,clrBrown,clrTan,clrMedi
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int N=5; // Number of ticks to change
input int bars_in_section=5; // The length of sections in bars
//--- An auxiliary variable to calculate ends of sections
int divider;
int color_sections;
//--- A buffer for plotting
double ColorSectionBuffer[];
//--- A buffer for storing the line color on each bar
double ColorSectionColors[];
//--- An array for storing colors contains 14 elements
color colors[]=
{
clrRed,clrBlue,clrGreen,clrChocolate,clrMagenta,clrDodgerBlue,clrGoldenrod,
clrIndigo,clrLightBlue,clrAliceBlue,clrMoccasin,clrWhiteSmoke,clrCyan,clrMediumPurple
};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorSectionBuffer,INDICATOR_DATA);
SetIndexBuffer(1,ColorSectionColors,INDICATOR_COLOR_INDEX);
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---- The number of colors to color the sections
int color_sections=8; // см. A comment to #property indicator_color1
//--- Check the indicator parameter
if(bars_in_section<=0)
{
PrintFormat("Invalid section length=%d",bars_in_section);
return(-1);
}
else divider=color_sections*bars_in_section;
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
//--- The number of the bar from which the calculation of indicator values starts
int start=0;
//--- If the indicator has been calculated before, then set start on the previous bar
if(prev_calculated>0) start=prev_calculated-1;
//--- Here are all the calculations of the indicator values
for(int i=start;i<rates_total;i++)
{
//--- If the bar number is divisible by the section_length, it means this is the end of the s
if(i%bars_in_section==0)
{
//--- Set the end of the section at the High price of this bar
ColorSectionBuffer[i]=high[i];
//--- A remainder of the division of the bar number by scetion_length*number_of_colors
int rest=i%divider;
//Get the number of the color = from 0 to number_of_colors-1
int color_indext=rest/bars_in_section;
ColorSectionColors[i]=color_indext;
}
//---If the remainder of the division is equal to bars,
else
{
//--- If nothing happened, ignore the bar - set 0
else ColorSectionBuffer[i]=0;
}
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the color of line segments |
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
int size=ArraySize(styles);
//--- Get the index to select a new style as the remainder of integer division
int style_index=number%size;
//--- Set the color as the PLOT_LINE_COLOR property
PlotIndexSetInteger(0,PLOT_LINE_STYLE,styles[style_index]);
//--- Write the line style
comm=EnumToString(styles[style_index])+", "+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
DRAW_COLOR_HISTOGRAM
The DRAW_COLOR_HISTOGRAM style draws a histogram as a sequence of colored columns from zero
to a specified value. Values are taken from the indicator buffer. Each column can have its own color
from a predefined set of colors.
The width, color and style of the histogram can be specified like for the DRAW_HISTOGRAM style -
using compiler directives or dynamically using the PlotIndexSetInteger() function. Dynamic changes of
the plotting properties allows changing the look of the histogram based on the current situation.
Since a column from the zero level is drawn on each bar, DRAW_COLOR_HISTOGRAM should better be
used in a separate chart window. Most often this type of plotting is used to create indicators of the
oscillator type, for example, Awesome Oscillator or Market Facilitation Index. For the empty non-
displayable values the zero value should be specified.
one buffer for storing a non-zero value of the vertical segment on each bar, the second end of the
segment is always on the zero line of the indicator;
one buffer to store the color index, which is used to draw the section (it makes sense to set only
non-empty values).
Colors can be specified using the compiler directive #property indicator_color1 separated by a comma.
The number of colors cannot exceed 64.
An example of the indicator that draws a sinusoid of a specified color based on the MathSin() function
. The color, width and style of all histogram columns change randomly each N ticks. The bars
parameter specifies the period of the sinusoid, that is after the specified number of bars the sinusoid
will repeat the cycle.
Please note that for plot1 with the DRAW_COLOR_HISTOGRAM style, 5 colors are set using the
compiler directive #property, and then in the OnCalculate() function the colors are selected randomly
from the 14 colors stored in the colors[] array. The N parameter is set in external parameters of the
indicator for the possibility of manual configuration (the Parameters tab in the indicator's Properties
window).
//+------------------------------------------------------------------+
//| DRAW_COLOR_HISTOGRAM.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 1
//--- input parameters
input int bars=30; // The period of a sinusoid in bars
input int N=5; // The number of ticks to change the histogram
//--- plot Color_Histogram
#property indicator_label1 "Color_Histogram"
#property indicator_type1 DRAW_COLOR_HISTOGRAM
//--- Define 8 colors for coloring sections (they are stored in a special array)
#property indicator_color1 clrRed,clrGreen,clrBlue,clrYellow,clrMagenta,clrCyan,clrMediumSeaGreen,
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- буфер значений
double Color_HistogramBuffer[];
//--- буфер индексов цветов
double Color_HistogramColors[];
//--- A factor to get the 2Pi angle in radians, when multiplied by the bars parameter
double multiplier;
int color_sections;
//--- An array for storing colors contains 14 elements
color colors[]=
{
clrRed,clrBlue,clrGreen,clrChocolate,clrMagenta,clrDodgerBlue,clrGoldenrod,
clrIndigo,clrLightBlue,clrAliceBlue,clrMoccasin,clrWhiteSmoke,clrCyan,clrMediumPurple
};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Color_HistogramBuffer,INDICATOR_DATA);
SetIndexBuffer(1,Color_HistogramColors,INDICATOR_COLOR_INDEX);
//---- The number of colors to color the sinusoid
color_sections=8; // см. A comment to #property indicator_color1
//--- Calculate the multiplier
if(bars>1)multiplier=2.*M_PI/bars;
else
{
PrintFormat("Set the value of bars=%d greater than 1",bars);
//--- Early termination of the indicator
return(-1);
}
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a critical number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Change colors used for the histogram
ChangeColors(colors,color_sections);
//--- Reset the counter of ticks to zero
ticks=0;
}
int start=0;
//--- If already calculated during the previous starts of OnCalculate
if(prev_calculated>0) start=prev_calculated-1; // set the beginning of the calculation with the
//--- Fill in the indicator buffer with values
for(int i=start;i<rates_total;i++)
{
//--- A value
Color_HistogramBuffer[i]=sin(i*multiplier);
//--- Color
int color_index=i%(bars*color_sections);
color_index/=bars;
Color_HistogramColors[i]=color_index;
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the color of line segments |
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the width of the line
int number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5; // The width is set from 0 to 4
//--- Set the color as the PLOT_LINE_WIDTH property
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,width);
//--- Write the line width
comm=comm+" Width="+IntegerToString(width);
DRAW_COLOR_HISTOGRAM2
The DRAW_COLOR_HISTOGRAM2 style draws a histogram of a specified color – vertical segments
using the values of two indicator buffers. But unlike the one-color DRAW_HISTOGRAM2, in this style
each column of the histogram can have its own color from a predefined set. The values of all the
segments are taken from the indicator buffer.
The width, style and color of the histogram can be specified like for theDRAW_HISTOGRAM2 style –
using compiler directives or dynamically using the PlotIndexSetInteger() function. Dynamic changes of
the plotting properties allows changing the look of the histogram based on the current situation.
The DRAW_COLOR_HISTOGRAM2 style can be used in a separate subwindow of a chart and in its main
window. For null values nothing is drawn, all the values in the indicator buffers need to be set
explicitly. Buffers are not initialized with a zero value.
two buffers to store the upper and lower end of the vertical segment on each bar;
onr buffer to store the color index, which is used to draw the segment (it makes sense to set only
non-empty values).
An example of the indicator that draws a histogram of a specified color between the High and Low
prices. For each weekday, the histogram lines have a different color. The color of the day, width and
style of the histogram change randomly each N ticks.
Please note that for plot1 with the DRAW_COLOR_HISTOGRAM2 style, 5 colors are set using the
compiler directive #property, and then in the OnCalculate() function the colors are selected randomly
from the 14 colors stored in the colors[] array.
The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_COLOR_HISTOGRAM2.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 1
//--- plot ColorHistogram_2
#property indicator_label1 "ColorHistogram_2"
#property indicator_type1 DRAW_COLOR_HISTOGRAM2
//--- Define 5 colors for coloring the histogram based on the weekdays (they are stored in the spec
#property indicator_color1 clrRed,clrBlue,clrGreen,clrYellow,clrMagenta
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
SetIndexBuffer(1,ColorHistogram_2Buffer2,INDICATOR_DATA);
SetIndexBuffer(2,ColorHistogram_2Colors,INDICATOR_COLOR_INDEX);
//--- Set an empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---- The number of colors to color the sinusoid
color_sections=8; // см. A comment to t#property indicator_color1
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a critical number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Change the colors used to draw the histogram
ChangeColors(colors,color_sections);
//--- Reset the counter of ticks to zero
ticks=0;
}
ColorHistogram_2Buffer1[i]=high[i];
ColorHistogram_2Buffer2[i]=low[i];
//--- Set the color index according to the weekday
int day=dt.day_of_week;
ColorHistogram_2Colors[i]=day;
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the color of line segments |
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
DRAW_COLOR_ARROW
The DRAW_COLOR_ARROW style draws colored arrows (symbols of the set Wingdings) based on the
value of the indicator buffer. In contrast to DRAW_ARROW, in this style it is possible to set a color
from a predefined set of colors specified by the indicator_color1 property for each symbol.
The width and color of the symbols can be specified like for theDRAW_ARROW style – using compiler
directives or dynamically using the PlotIndexSetInteger() function. Dynamic changes of the plotting
properties allows changing the look of an indicator based on the current situation.
//--- Define the symbol code from the Wingdings font to draw in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
Each arrow is actually a symbol that has the height and the anchor point, and can cover some
important information on a chart (for example, the closing price at the bar). Therefore, we can
additionally specify the vertical shift in pixels, which does not depend on the scale of the chart. The
arrows will be shifted down by the specified number of pixels, although the values of the indicator will
remain the same:
A negative value of PLOT_ARROW_SHIFT means the shift of arrows upwards, a positive values shifts
the arrow down.
The DRAW_COLOR_ARROW style can be used in a separate subwindow of a chart and in its main
window. Null values are not drawn and do not appear in the "Data Window", all the values in the
indicator buffers should be set explicitly. Buffers are not initialized with a zero value.
a buffer to store the value of the price which is used to draw the symbol (plus a shift in pixels,
given in the PLOT_ARROW_SHIFT property);
a buffer to store the color index, which is used to draw an arrow (it makes sense to set only non-
empty values).
An example of the indicator, which draws arrows on each bar with the the close price higher than the
close price of the previous bar. The width, shift and symbol code of all arrows are changed randomly
every N ticks. The color of the symbol depends on the number of the bar on which it is drawn.
In the example, for plot1 with the DRAW_COLOR_ARROW style, the properties, color and size are
specified using the compiler directive #property, and then in the OnCalculate() function the properties
are set randomly. The N parameter is set in external parameters of the indicator for the possibility of
manual configuration (the Parameters tab in the indicator's Properties window).
Please note that initially 8 colors are ser using the compiler directive #property, and then in the
OnCalculate() function, the color is set randomly from the 14 colors that are stored in the colors[]
array.
//+------------------------------------------------------------------+
//| DRAW_COLOR_ARROW.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//--- plot ColorArrow
#property indicator_label1 "ColorArrow"
#property indicator_type1 DRAW_COLOR_ARROW
//--- Define 8 colors for coloring the histogram based on the weekdays (they are stored in the spec
#property indicator_color1 clrRed,clrBlue,clrSeaGreen,clrGold,clrDarkOrange,clrMagenta,clrYellowGr
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
for(int plot_color_ind=0;plot_color_ind<plot_colors;plot_color_ind++)
{
//--- Get a random value
int number=MathRand();
//--- Get an index in the col[] array as a remainder of the integer devision
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0, // The number of a graphical style
PLOT_LINE_COLOR, // Property identifier
plot_color_ind, // The index of the color, where we write the colo
cols[i]); // A new color
//--- Write the colors
comm=comm+StringFormat("ArrowColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],tru
ChartSetString(0,CHART_COMMENT,comm);
}
//---
}
//+------------------------------------------------------------------+
//| Changes the appearance of a displayed line in the indicator |
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the width of the line
int number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5; // The width is set from 0 to 4
//--- Set the color as the PLOT_LINE_WIDTH property
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,width);
//--- Write the line width
comm=comm+" Width="+IntegerToString(width);
DRAW_COLOR_ZIGZAG
The DRAW_COLOR_ZIGZAG style draws segments of different colors, using the values of two indicator
buffers. This style is a colored version of DRAW_ZIGZAG, i.e. allows specifying for each segment an
individual color from the predefined set of colors. The segments are plotted from a value in the first
buffer to a value in the second indicator buffer. None of the buffers can contain only null values, since
in this case nothing is plotted.
The width, color and style of the line can be specified like for the DRAW_ZIGZAG style - using compiler
directives or dynamically using the PlotIndexSetInteger() function. Dynamic changes of the plotting
properties allows "to enliven" indicators, so that their appearance changes depending on the current
situation.
Sections are drawn from a non-null value of one buffer to a non-null value of another indicator buffer.
To specify what value should be considered as "empty", set this value in the PLOT_EMPTY_VALUE
property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
two buffers to store the values values of ends of the zigzag sections;
one buffer to store the color index, which is used to draw the section (it makes sense to set only
non-empty values).
An example of the indicator that plots a saw based on the High and Low prices. The color, width and
style of the zigzag lines change randomly every N ticks.
Please note that for plot1 with the DRAW_COLOR_ZIGZAG style, 8 colors are set using the compiler
directive #property, and then in the OnCalculate() function the color is selected randomly from the 14
colors stored in the colors[] array.
The N parameter is set in external parameters of the indicator for the possibility of manual
configuration (the Parameters tab in the indicator's Properties window).
//+------------------------------------------------------------------+
//| DRAW_COLOR_ZIGZAG.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 1
//--- plot Color_Zigzag
#property indicator_label1 "Color_Zigzag"
#property indicator_type1 DRAW_COLOR_ZIGZAG
//--- Define 8 colors for coloring sections (they are stored in a special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrYellow,clrMagenta,clrCyan,clrLime,clrOrange
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameter
input int N=5; // Number of ticks to change
int color_sections;
//--- Buffers of values of segment ends
double Color_ZigzagBuffer1[];
double Color_ZigzagBuffer2[];
//--- Buffers of color indexes of segment ends
double Color_ZigzagColors[];
//--- An array for storing colors contains 14 elements
color colors[]=
{
clrRed,clrBlue,clrGreen,clrChocolate,clrMagenta,clrDodgerBlue,clrGoldenrod,
clrIndigo,clrLightBlue,clrAliceBlue,clrMoccasin,clrWhiteSmoke,clrCyan,clrMediumPurple
};
//--- An array to store the line styles
ENUM_LINE_STYLE styles[]={STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Color_ZigzagBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,Color_ZigzagBuffer2,INDICATOR_DATA);
SetIndexBuffer(2,Color_ZigzagColors,INDICATOR_COLOR_INDEX);
//---- количество цветов для раскраски зигзага
color_sections=8; // см. A comment to the #property indicator_color1 property
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the style, color and width of the line
ticks++;
//--- If a sufficient number of ticks has been accumulated
if(ticks>=N)
{
//--- Change the line properties
ChangeLineAppearance();
//--- Change colors used to plot the sections
ChangeColors(colors,color_sections);
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- The structure of time is required to get the weekday of each bar
MqlDateTime dt;
{
//--- Write the bar open time in the structure
TimeToStruct(time[i],dt);
DRAW_COLOR_BARS
The DRAW_COLOR_BARS style draws bars on the values of four indicator buffers, which contain the
Open, High, Low and Close prices. This style is an advanced version of DRAW_BARS and allows
specifying for each bar an individual color from the predefined set of colors. It used for creating
custom indicators as bars, including those in a separate subwindow of a chart and on other financial
instruments.
The color of bars can be set using the compiler directives or dynamically using the PlotIndexSetInteger
() function. Dynamic changes of the plotting properties allows "to enliven" indicators, so that their
appearance changes depending on the current situation.
The indicator is drawn only to those bars, for which non-empty values of all four indicator buffers are
set. To specify what value should be considered as "empty", set this value in the PLOT_EMPTY_VALUE
property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
four buffer to store the values of Open, High, Low and Close;
one buffer to store the color index, which is used to draw a bar (it makes sense to set it only for the
bars that will be drawn).
All buffers for the plotting should go one after the other in the given order: Open, High, Low, Close
and the color buffer. None of the price buffers can contain only null values, since in this case nothing
is plotted.
An example of the indicator that draws bars on a selected financial instrument in a separate window.
The color of bars changes randomly every N ticks. The N parameter is set in external parameters of
the indicator for the possibility of manual configuration (the Parameters tab in the indicator's
Properties window).
Please note that for plot1 with the DRAW_COLOR_BARS style, 8 colors are set using the compiler
directive #property, and then in the OnCalculate() function the color is selected randomly from the 14
colors stored in the colors[] array.
//+------------------------------------------------------------------+
//| DRAW_COLOR_BARS.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots 1
//--- plot ColorBars
#property indicator_label1 "ColorBars"
#property indicator_type1 DRAW_COLOR_BARS
//--- Define 8 colors for coloring bars (they are stored in the special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrYellow,clrMagenta,clrCyan,clrLime,clrOrange
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
name,
copied,
bars
);
//--- Show a message in a comment in the main chart window
Comment(comm);
//--- Show the message
if(messages) Print(comm);
return(false);
}
else
{
//--- Set the display of the symbol
PlotIndexSetString(0,PLOT_LABEL,name+" Open;"+name+" High;"+name+" Low;"+name+" Close");
IndicatorSetString(INDICATOR_SHORTNAME,"DRAW_COLOR_BARS("+name+")");
}
//--- Initialize buffers with empty values
ArrayInitialize(ColorBarsBuffer1,0.0);
ArrayInitialize(ColorBarsBuffer2,0.0);
ArrayInitialize(ColorBarsBuffer3,0.0);
ArrayInitialize(ColorBarsBuffer4,0.0);
}
//+------------------------------------------------------------------+
//| Changes the color of the zigzag segments
//+------------------------------------------------------------------+
void ChangeColors(color &cols[],int plot_colors)
{
//--- The number of colors
int size=ArraySize(cols);
//---
string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
DRAW_COLOR_CANDLES
The DRAW_COLOR_CANDLES style, like DRAW_CANDLES, draws candlesticks using the values of four
indicator buffers, which contain Open, High, Low and Close prices. In addition, it allows specifying a
color for each candlestick from a given set. For this purpose, the style has a special color buffer that
stores color indexes for each bar. It used for creating custom indicators as a sequence of candlesticks,
including those in a separate subwindow of a chart and on other financial instruments.
The number of colors of candlesticks can be set using the compiler directives or dynamically using the
PlotIndexSetInteger() function. Dynamic changes of the plotting properties allows "to enliven"
indicators, so that their appearance changes depending on the current situation.
The indicator is drawn only to those bars, for which non-empty values of four price buffers of the
indicator are set. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property:
Always explicitly fill in the values of the indicator buffers, set a null value in a buffer to skip bars.
four buffer to store the values of Open, High, Low and Close;
one buffer to store the color index, which is used to draw a candlestick (it makes sense to set it
only for the candlesticks that will be drawn).
All buffers for the plotting should go one after the other in the given order: Open, High, Low, Close
and the color buffer. None of the price buffers can contain only null values, since in this case nothing
is plotted.
An example of the indicator that draws candlesticks for a selected financial instrument in a separate
window. The color of candlesticks changes randomly every N ticks. The N parameter is set in external
parameters of the indicator for the possibility of manual configuration (the Parameters tab in the
indicator's Properties window).
Please note that for plot1, the color is set using the compiler directive #property, and then in the
OnCalculate() function the color is set randomly from an earlier prepared list.
//+------------------------------------------------------------------+
//| DRAW_COLOR_CANDLES.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots 1
//--- plot ColorCandles
#property indicator_label1 "ColorCandles"
#property indicator_type1 DRAW_COLOR_CANDLES
//--- Define 8 colors for coloring candlesticks (they are stored in the special array)
#property indicator_color1 clrRed,clrBlue,clrGreen,clrYellow,clrMagenta,clrCyan,clrLime,clrOrange
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=INT_MAX-100;
//--- Count ticks to change the style and color
ticks++;
//--- If a sufficient number of ticks has been accumulated
if(ticks>=N)
{
//--- Select a new symbol from the Market watch window
symbol=GetRandomSymbolName();
//--- Change the form
ChangeLineAppearance();
//--- Change the colors used to draw the candlesticks
ChangeColors(colors,candles_colors);
int tries=0;
//--- Make 5 attempts to fill in the buffers of plot1 with the prices from symbol
while(!CopyFromSymbolToBuffers(symbol,rates_total,0,
ColorCandlesBuffer1,ColorCandlesBuffer2,ColorCandlesBuffer3,
ColorCandlesBuffer4,ColorCandlesColors,candles_colors)
&& tries<5)
{
//--- A counter of calls of the CopyFromSymbolToBuffers() function
tries++;
}
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Fills in the specified candlestick |
//+------------------------------------------------------------------+
bool CopyFromSymbolToBuffers(string name,
int total,
int plot_index,
double &buff1[],
double &buff2[],
double &buff3[],
double &buff4[],
double &col_buffer[],
int cndl_colors
)
{
//--- In the rates[] array, we will copy Open, High, Low and Close
MqlRates rates[];
//--- The counter of attempts
int attempts=0;
//--- How much has been copied
int copied=0;
//--- Make 25 attempts to get a timeseries on the desired symbol
while(attempts<25 && (copied=CopyRates(name,_Period,0,bars,rates))<0)
{
Sleep(100);
attempts++;
if(messages) PrintFormat("%s CopyRates(%s) attempts=%d",__FUNCTION__,name,attempts);
}
//--- If failed to copy a sufficient number of bars
if(copied!=bars)
{
//--- Form a message string
string comm=StringFormat("For the symbol %s, managed to receive only %d bars of %d requested
name,
copied,
bars
);
//--- Show a message in a comment in the main chart window
Comment(comm);
//--- Show the message
if(messages) Print(comm);
return(false);
}
else
{
//--- Set the display of the symbol
PlotIndexSetString(plot_index,PLOT_LABEL,name+" Open;"+name+" High;"+name+" Low;"+name+" Clos
IndicatorSetString(INDICATOR_SHORTNAME,"DRAW_COLOR_CANDLES("+symbol+")");
}
//--- Initialize buffers with empty values
ArrayInitialize(buff1,0.0);
ArrayInitialize(buff2,0.0);
ArrayInitialize(buff3,0.0);
ArrayInitialize(buff4,0.0);
SetIndexBuffer
The function binds a specified indicator buffer with one-dimensional dynamic array of the double type
announced at the global level.
bool SetIndexBuffer(
int index, // buffer index
double buffer[], // array
ENUM_INDEXBUFFER_TYPE data_type // what will be stored
);
Parameters
index
[in] Number of the indicator buffer. The numbering starts with 0. The number must be less than
the value declared in #property indicator_buffers.
buffer[]
[in] An array declared in the custom indicator program.
data_type
[in] Type of data stored in the indicator array. By default it is INDICATOR_DATA (values of the
calculated indicator). It may also take the value of INDICATOR_COLOR_INDEX; in this case this
buffer is used for storing color indexes for the previous indicator buffer. You can specify up to 64
colors in the #property indicator_colorN line. The INDICATOR_CALCULATIONS value means that the
buffer is used in intermediate calculations of the indicator and is not intended for drawing.
Return Value
Note
After binding, the dynamic array buffer[] will be indexed as in common arrays, even if the indexing
of timeseries is pre-installed for the bound array. If you want to change the order of access to
elements of the indicator array, use the ArraySetAsSeries() function after binding the array using
the SetIndexBuffer() function. Please note that you can't change the size for dynamic arrays set as
indicator buffers by the function SetIndexBuffer(). For indicator buffers, all operations of size
changes are performed by the executing sub-system of the terminal.
Example:
//+------------------------------------------------------------------+
//| TestCopyBuffer1.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot MA
#property indicator_label1 "MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input bool AsSeries=true;
input int period=15;
input ENUM_MA_METHOD smootMode=MODE_EMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
input int shift=0;
//--- indicator buffers
double MABuffer[];
int ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
if(AsSeries) ArraySetAsSeries(MABuffer,true);
Print("Indicator buffer is timeseries = ",ArrayGetAsSeries(MABuffer));
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("Indicator buffer after SetIndexBuffer() is timeseries = ",
ArrayGetAsSeries(MABuffer));
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//---
ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
See also
IndicatorSetDouble
The function sets the value of the corresponding indicator property. Property of the indicator should
be of the double type. There are 2 variants of the function.
bool IndicatorSetDouble(
int prop_id, // identifier
double prop_value // value to be set
);
bool IndicatorSetDouble(
int prop_id, // identifier
int prop_modifier, // modifier
double prop_value // value to be set
)
Parameters
prop_id
[in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_DOUBLE
enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
prop_value
[in] The value of the property.
Return Value
IndicatorSetInteger
The function sets the value of the corresponding indicator property. The property must be of int or
color type. There are 2 variants of the function.
bool IndicatorSetInteger(
int prop_id, // identifier
int prop_value // value to be set
);
bool IndicatorSetInteger(
int prop_id, // identifier
int prop_modifier, // modifier
int prop_value // value to be set
)
Parameters
prop_id
[in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_INTEGER
enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
prop_value
[in] The value of the property.
Return Value
IndicatorSetString
The function sets the value of a corresponding indicator property. The indicator property must be of
the string type. There are 2 variants of the function.
bool IndicatorSetString(
int prop_id, // identifier
string prop_value // value to be set
);
bool IndicatorSetString(
int prop_id, // identifier
int prop_modifier, // modifier
string prop_value // value to be set
)
Parameters
prop_id
[in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_STRING
enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
prop_value
[in] The value of the property.
Return Value
PlotIndexSetDouble
The function sets the value of the corresponding property of the corresponding indicator line. The
indicator property must be of the double type.
bool PlotIndexSetDouble(
int plot_index, // plotting style index
int prop_id, // property identifier
double prop_value // value to be set
);
Parameters
plot_index
[in] Index of the graphical plotting
prop_id
[in] The value can be one of the values of the ENUM_PLOT_PROPERTY_DOUBLE enumeration.
prop_value
[in] The value of the property.
Return Value
PlotIndexSetInteger
The function sets the value of the corresponding property of the corresponding indicator line. The
indicator property must be of the int, char, bool or color type. There are 2 variants of the function.
bool PlotIndexSetInteger(
int plot_index, // plotting style index
int prop_id, // property identifier
int prop_value // value to be set
);
bool PlotIndexSetInteger(
int plot_index, // plotting style index
int prop_id, // property identifier
int prop_modifier, // property modifier
int prop_value // value to be set
)
Parameters
plot_index
[in] Index of the graphical plotting
prop_id
[in] The value can be one of the values of the ENUM_PLOT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
prop_value
[in] The value of the property.
Return Value
Example: an indicator that draws a three-color line. The color scheme changes every 5 ticks.
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//---- plot ColorLine
#property indicator_label1 "ColorLine"
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 clrRed,clrGreen,clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 3
//--- indicator buffers
double ColorLineBuffer[];
double ColorBuffer[];
int MA_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorLineBuffer,INDICATOR_DATA);
SetIndexBuffer(1,ColorBuffer,INDICATOR_COLOR_INDEX);
//--- get MA handle
MA_handle=iMA(Symbol(),0,10,0,MODE_EMA,PRICE_CLOSE);
//---
}
//+------------------------------------------------------------------+
//| get color index |
//+------------------------------------------------------------------+
int getIndexOfColor(int i)
{
int j=i%300;
if(j<100) return(0);// first index
if(j<200) return(1);// second index
return(2); // third index
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
static int ticks=0,modified=0;
int limit;
//--- first calculation or number of bars was changed
if(prev_calculated==0)
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);// copying failed - throw away
//--- now set line color for every bar
for(int i=0;i<rates_total;i++)
ColorBuffer[i]=getIndexOfColor(i);
}
else
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);
{
case 0:// first color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrRed);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrBlue);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrGreen);
Print("Color scheme "+modified);
break;
case 1:// second color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrYellow);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrPink);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrLightSlateGray);
Print("Color scheme "+modified);
break;
default:// third color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrLightGoldenrod);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrOrchid);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrLimeGreen);
Print("Color scheme "+modified);
}
}
else
{
//--- set start position
limit=prev_calculated-1;
//--- now we set line color for every bar
for(int i=limit;i<rates_total;i++)
ColorBuffer[i]=getIndexOfColor(i);
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
PlotIndexSetString
The function sets the value of the corresponding property of the corresponding indicator line. The
indicator property must be of the string type.
bool PlotIndexSetString(
int plot_index, // plotting style index
int prop_id, // property identifier
string prop_value // value to be set
);
Parameters
plot_index
[in] Index of graphical plot
prop_id
[in] The value can be one of the values of the ENUM_PLOT_PROPERTY_STRING enumeration.
prop_value
[in] The value of the property.
Return Value
PlotIndexGetInteger
The function sets the value of the corresponding property of the corresponding indicator line. The
indicator property must be of the int, color, bool or char type. There are 2 variants of the function.
int PlotIndexGetInteger(
int plot_index, // plotting style index
int prop_id, // property identifier
);
int PlotIndexGetInteger(
int plot_index, // plotting index
int prop_id, // property identifier
int prop_modifier // property modifier
)
Parameters
plot_index
[in] Index of the graphical plotting
prop_id
[in] The value can be one of the values of the ENUM_PLOT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
Note
Function is designed to extract the settings of drawing of the appropriate indicator line. The
function works in tandem with the function PlotIndexSetInteger to copy the drawing properties of
one line to another.
Example: an indicator that colors candles depending on the day of the week. Colors for each day are
set in a program way.
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots 1
//---- plot ColorCandles
#property indicator_label1 "ColorCandles"
#property indicator_type1 DRAW_COLOR_CANDLES
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double OpenBuffer[];
double HighBuffer[];
double LowBuffer[];
double CloseBuffer[];
double ColorCandlesColors[];
color ColorOfDay[6]={CLR_NONE,clrMediumSlateBlue,
clrDarkGoldenrod,clrForestGreen,clrBlueViolet,clrRed};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,OpenBuffer,INDICATOR_DATA);
SetIndexBuffer(1,HighBuffer,INDICATOR_DATA);
SetIndexBuffer(2,LowBuffer,INDICATOR_DATA);
SetIndexBuffer(3,CloseBuffer,INDICATOR_DATA);
SetIndexBuffer(4,ColorCandlesColors,INDICATOR_COLOR_INDEX);
//--- set number of colors in color buffer
PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,6);
//--- set colors for color buffer
for(int i=1;i<6;i++)
PlotIndexSetInteger(0,PLOT_LINE_COLOR,i,ColorOfDay[i]);
//--- set accuracy
IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
printf("We have %u colors of days",PlotIndexGetInteger(0,PLOT_COLOR_INDEXES));
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int i;
MqlDateTime t;
//----
if(prev_calculated==0) i=0;
else i=prev_calculated-1;
//----
while(i<rates_total)
{
OpenBuffer[i]=open[i];
HighBuffer[i]=high[i];
LowBuffer[i]=low[i];
CloseBuffer[i]=close[i];
//--- set color for every candle
TimeToStruct(time[i],t);
ColorCandlesColors[i]=t.day_of_week;
//---
i++;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
Object Functions
This is the group of functions intended for working with graphic objects relating to any specified
chart.
Function Action
Every graphical object should have a name unique within one chart, including its subwindows.
Changing of a name of a graphic object generates two events: event of deletion of an object with the
old name, and event of creation of an object with a new name.
After an object is created or an object property is modified it is recommended to call the ChartRedraw
() function, which commands the client terminal to forcibly draw a chart (and all visible objects in it).
ObjectCreate
The function creates an object with the specified name, type, and the initial coordinates in the
specified chart subwindow. During creation up to 30 coordinates can be specified.
bool ObjectCreate(
long chart_id, // chart identifier
string name, // object name
int type, // object type
int nwin, // window index
datetime time1, // time of the first anchor point
double price1, // price of the first anchor point
...
datetime timeN=0, // time of the N-th anchor point
double priceN=0, // price of the N-th anchor point
...
datetime time30=0, // time of the 30th anchor point
double price30=0 // price of the 30th anchor point
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object. The name must be unique within a chart, including its subwindows.
type
[in] Object type. The value can be one of the values of the ENUM_OBJECT enumeration.
nwin
[in] Number of the chart subwindow. 0 means the main chart window. The specified subwindow
must exist, otherwise the function returns false.
time1
[in] The time coordinate of the first anchor.
price1
[in] The price coordinate of the first anchor point.
timeN=0
[in] The time coordinate of the N-th anchor point.
priceN=0
[in] The price coordinate of the N-th anchor point.
time30=0
[in] The time coordinate of the thirtieth anchor point.
price30=0
[in] The price coordinate of the thirtieth anchor point.
Return Value
Returns true or false depending on whether the object is created or not. To read more about the
error call GetLastError(). If the object has been created already, the function tries to change its
coordinates.
Note
The numbering of the chart subwindows (if there are subwindows with indicators in the chart) starts
with 1. The main chart window of the chart is and always has index 0.
The large number of anchor points (up to 30) is implemented for future use. At the same time, the
limit of 30 possible anchor points for graphical objects is determined by the limit on the number of
parameters (not more than 64) that can be used when calling a fucntion.
When an object is renamed, two events are formed simultaneously. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
ObjectName
The function returns the name of the corresponding object in the specified chart, in the specified
subwindow, of the specified type.
string ObjectName(
long chart_id, // chart identifier
int pos, // number in the list of objects
int nwin=-1, // window index
int type=-1 // object type
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
pos
[in] Ordinal number of the object according to the specified filter by the number and type of the
subwindow.
nwin=-1
[in] Number of the chart subwindow. 0 means the main chart window, -1 means all the
subwindows of the chart, including the main window.
type=-1
[in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1
means all types.
Return Value
Note
When an object is renamed, two events are formed simultaneously. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
ObjectDelete
The function removes the object with the specified name from the specified chart.
bool ObjectDelete(
long chart_id, // chart identifier
string name // object name
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of object to be deleted.
Return Value
Returns true if the removal was successful, otherwise returns false. To read more about the error
call GetLastError().
Note
When an object is renamed, two events are formed simultaneously. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
ObjectsDeleteAll
Removes all objects from the specified chart, specified chart subwindow, of the specified type.
int ObjectsDeleteAll(
long chart_id, // chart identifier
int nwin=-1, // window index
int type=-1 // object type
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
nwin=-1
[in] Number of the chart subwindow. 0 means the main chart window, -1 means all the subwindows
of the chart, including the main window.
type=-1
[in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1
means all types.
Return Value
Returns the number of deleted objects. To read more about the error call GetLastError().
ObjectFind
The function searches for an object with the specified name in the chart with the specified ID.
int ObjectFind(
long chart_id, // chart identifier
string name // object name
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] The name of the searched object.
Return Value
If successful the function returns the number of the subwindow (0 means the main window of the
chart), in which the object is found. If the object is not found, the function returns a negative
number. To read more about the error call GetLastError().
Note
When an object is renamed, two events are formed simultaneously. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
ObjectGetTimeByValue
The function returns the time value for the specified price value of the specified object.
datetime ObjectGetTimeByValue(
long chart_id, // chart identifier
string name, // object name
double value, // Price
int line_id // Line number
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
value
[in] Price value.
line_id
[in] Line identifier.
Return Value
The time value for the specified price value of the specified object.
Note
An object can have several values in one price coordinate, therefore it is necessary to specify the
line number. This function applies only to the following objects:
Trendline (OBJ_TREND)
Trendline by angle (OBJ_TRENDBYANGLE)
Gann line (OBJ_GANNLINE)
Equidistant channel (OBJ_CHANNEL) - 2 lines
Liner regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
Arrowed line (OBJ_ARROWED_LINE)
See also
Object Types
ObjectGetValueByTime
The function returns the price value for the specified time value of the specified object.
double ObjectGetValueByTime(
long chart_id, // chart identifier
string name, // object name
datetime time, // Time
int line_id // Line number
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
time
[in] Time value.
line_id
[in] Line ID.
Return Value
The price value for the specified time value of the specified object.
Note
An object can have several values in one price coordinate, therefore it is necessary to specify the
line number. This function applies only to the following objects:
Trendline (OBJ_TREND)
Trendline by angle (OBJ_TRENDBYANGLE)
Gann line (OBJ_GANNLINE)
Equidistant channel (OBJ_CHANNEL) - 2 lines
Liner regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
Arrowed line (OBJ_ARROWED_LINE)
See also
Object Types
ObjectMove
The function changes coordinates of the specified anchor point of the object.
bool ObjectMove(
long chart_id, // chart identifier
string name, // object name
int point_index, // anchor point number
datetime time, // Time
double price // Price
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
point_index
[in] Index of the anchor point. The number of anchor points depends on the type of object.
time
price
[in] Price coordinate of the selected anchor point.
Return Value
If successful, returns true, in case of failure returns false. To read more about the error call
GetLastError().
ObjectsTotal
The function returns the number of objects in the specified chart, specified subwindow, of the
specified type.
int ObjectsTotal(
long chart_id, // chart identifier
int nwin=-1, // window index
int type=-1 // object type
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
nwin=-1
[in] Number of the chart subwindow. 0 means the main chart window, -1 means all the
subwindows of the chart, including the main window.
type=-1
[in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1
means all types.
Return Value
ObjectSetDouble
The function sets the value of the corresponding object property. The object property must be of the
double type. There are 2 variants of the function.
bool ObjectSetDouble(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
double prop_value // value
);
bool ObjectSetDouble(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
int prop_modifier, // modifier
double prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and
in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a graphical object has been
sent to a chart successfully. Otherwise it returns false. To read more about the error call
GetLastError().
void OnStart()
{
//--- auxiliary arrays
double high[],low[],price1,price2;
datetime time[],time1,time2;
//--- Copy the open prices - 100 latest bars are enough
int copied=CopyHigh(Symbol(),0,0,100,high);
if(copied<=0)
{
Print("Failed to copy the values of the High price series");
return;
}
//--- Copy the close price - 100 latest bars are enough
copied=CopyLow(Symbol(),0,0,100,low);
if(copied<=0)
{
Print("Failed to copy the values of the Low price series");
return;
}
//--- Copy the open time for the last 100 bars
copied=CopyTime(Symbol(),0,0,100,time);
if(copied<=0)
{
Print("Failed to copy the values of the price series of Time");
return;
}
//--- Organize access to the copied data as to timeseries - backwards
ArraySetAsSeries(high,true);
ArraySetAsSeries(low,true);
ArraySetAsSeries(time,true);
for(int i=0;i<levels;i++)
{
Print(i,": ",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i),
" ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i));
}
//--- Try to increase the number of levels per unit
bool modified=ObjectSetInteger(0,"Fibo",OBJPROP_LEVELS,levels+1);
if(!modified) // failed to change the number of levels
{
Print("Failed to change the number of levels of Fibo, error ",GetLastError());
}
//--- just inform
Print("Fibo levels after = ",ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS));
//--- set a value for a newly created level
bool added=ObjectSetDouble(0,"Fibo",OBJPROP_LEVELVALUE,levels,133);
if(added) // managed to set a value for the level
{
Print("Successfully set one more Fibo level");
//--- Also do not forget to set the level description
ObjectSetString(0,"Fibo",OBJPROP_LEVELTEXT,levels,"my level");
ChartRedraw(0);
//--- Get the actual value of the number of levels in the Fibo object
levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS);
Print("Fibo levels after adding = ",levels);
//--- once again output all levels - just to make sure
for(int i=0;i<levels;i++)
{
Print(i,":",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i),
" ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i));
}
}
else // Fails if you try to increase the number of levels in the Fibo object
{
Print("Failed to set one more Fibo level. Error ",GetLastError());
}
}
}
See also
Object Types, Object Properties
ObjectSetInteger
The function sets the value of the corresponding object property. The object property must be of the
datetime, int, color, bool or char type. There are 2 variants of the function.
bool ObjectSetInteger(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
long prop_value // value
);
bool ObjectSetInteger(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
int prop_modifier, // modifier
long prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and
in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a graphical object has been
sent to a chart successfully. Otherwise it returns false. To read more about the error call
GetLastError().
See also
Object Types, Object Properties
ObjectSetString
The function sets the value of the corresponding object property. The object property must be of the
string type. There are 2 variants of the function.
bool ObjectSetString(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
string prop_value // value
);
bool ObjectSetString(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property
int prop_modifier, // modifier
string prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_STRING enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and
in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a graphical object has been
sent to a chart successfully. Otherwise it returns false. To read more about the error call
GetLastError().
Note
When an object is renamed, two events are formed simultaneously. TThese events can be handled
in an Expert Advisor or indicator by the OnChartEvent() function:
ObjectGetDouble
The function returns the value of the corresponding object property. The object property must be of
the double type. There are 2 variants of the function.
double ObjectGetDouble(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
2. Returns true or false, depending on the success of the function. If successful, the property
value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetDouble(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier, // property modifier
double& double_var // here we accept the property value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default modifier value is equal to
0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools
and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
double_var
[out] Variable of the double type that received the value of the requested property.
Return Value
For the second variant the function returns true, if this property is maintained and the value has
been placed into the double_var variable, otherwise returns false. To read more about the error call
GetLastError().
ObjectGetInteger
The function returns the value of the corresponding object property. The object property must be of
the datetime, int, color, bool or char type. There are 2 variants of the function.
long ObjectGetInteger(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
2. Returns true or false, depending on the success of the function. If successful, the property
value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetInteger(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier, // property modifier
long& long_var // here we accept the property value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default modifier value is equal to
0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools
and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
long_var
[out] Variable of the long type that receives the value of the requested property.
Return Value
For the second variant the function returns true, if this property is maintained and the value has
been placed into the long_var variable, otherwise returns false. To read more about the error call
GetLastError().
ObjectGetString
The function returns the value of the corresponding object property. The object property must be of
the string type. There are 2 variants of the function.
string ObjectGetString(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
2. Returns true or false, depending on the success of the function. If successful, the property
value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetString(
long chart_id, // chart identifier
string name, // object name
int prop_id, // property identifier
int prop_modifier, // property modifier
string& string_var // here we accept the property value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_STRING enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default modifier value is equal to
0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools
and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero.
string_var
[out] Variable of the string type that receives the value of the requested properties.
Return Value
For the second version of the call returns true, if this property is maintained and the value has been
placed into the string_var variable, otherwise returns false. To read more about the error call
GetLastError().
Note
When an object is renamed, two events are formed simultaneously. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
These functions return the handle of the appropriate copy of the indicator. Further, using this handle,
you can receive data calculated by the corresponding indicator. The corresponding buffer data
(technical indicators contain calculated data in their internal buffers, which can vary from 1 to 5,
depending on the indicator) can be copied to a mql5-program using the CopyBuffer() function.
You can't refer to the indicator data right after it has been created, because calculation of indicator
values requires some time, so it's better to create indicator handles in OnInit(). Function iCustom()
creates the corresponding custom indicator, and returns its handle in case it is successfully create.
Custom indicators can contain up to 512 indicator buffers, the contents of which can also be obtained
by the CopyBuffer() function, using the obtained handle.
There is a universal method for creating any technical indicator using the IndicatorCreate() function.
This function accepts the following data as input parameters:
symbol name;
timeframe;
type of the indicator to create;
number of input parameters of the indicator;
an array of MqlParam type containing all the necessary input parameters.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note. Repeated call of the indicator function with the same parameters within one mql5-program does
not lead to a multiple increase of the reference counter; the counter will be increased only once by 1.
However, it's recommended to get the indicators handles in function OnInit() or in the class
constructor, and further use these handles in other functions. The reference counter decreases when a
mql5-program is deinitialized.
All indicator functions have at least 2 parameters - symbol and period. The NULL value of the symbol
means the current symbol, the 0 value of the period means the current timeframe.
iAD Accumulation/Distribution
iAlligator Alligator
iDeMarker DeMarker
iEnvelopes Envelopes
iFractals Fractals
iMomentum Momentum
iVolumes Volumes
iAC
The function creates Accelerator Oscillator in a global cache of the client terminal and returns its
handle. It has only one buffer.
int iAC(
string symbol, // symbol name
ENUM_TIMEFRAMES period // period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means
the current timeframe.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iAD
The function returns the handle of the Accumulation/Distribution indicator. It has only one buffer.
int iAD(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means
the current timeframe.
applied_volume
[in] The volume used. Can be any of ENUM_APPLIED_VOLUME values.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iADX
The function returns the handle of the Average Directional Movement Index indicator.
int iADX(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int adx_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
adx_period
[in] Period to calculate the index.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iADXWilder
The function returns the handle of Average Directional Movement Index by Welles Wilder.
int iADXWilder(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int adx_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
adx_period
[in] Period to calculate the index.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iAlligator
The function returns the handle of the Alligator indicator.
int iAlligator(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int jaw_period, // period for the calculation of jaws
int jaw_shift, // horizontal shift of jaws
int teeth_period, // period for the calculation of teeth
int teeth_shift, // horizontal shift of teeth
int lips_period, // period for the calculation of lips
int lips_shift, // horizontal shift of lips
ENUM_MA_METHOD ma_method, // type of smoothing
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
jaw_period
[in] Averaging period for the blue line (Alligator's Jaw)
jaw_shift
[in] The shift of the blue line relative to the price chart. It should be remembered that the line
shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining
buffer values using the CopyBuffer() function,the shift value will have no effect.
teeth_period
[in] Averaging period for the red line (Alligator's Teeth).
teeth_shift
[in] The shift of the red line relative to the price chart. It should be remembered that the line
shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining
buffer values using the CopyBuffer() function,the shift value will have no effect.
lips_period
[in] Averaging period for the green line (Alligator's lips).
lips_shift
[in] The shift of the green line relative to the price chart. It should be remembered that the line
shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining
buffer values using the CopyBuffer() function,the shift value will have no effect.
ma_method
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iAMA
The function returns the handle of the Adaptive Moving Average indicator. It has only one buffer.
int iAMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ama_period, // average period for AMA
int fast_ma_period, // fast MA period
int slow_ma_period, // slow MA period
int ama_shift, // horizontal shift of the indicator
ENUM_APPLIED_PRICE applied_price // type of the price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ama_period
[in] The calculation period, on which the efficiency coefficient is calculated.
fast_ma_period
[in] Fast period for the smoothing coefficient calculation for a rapid market.
slow_ma_period
[in] Slow period for the smoothing coefficient calculation in the absence of trend.
ama_shift
[in] Shift of the indicator relative to the price chart.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iAO
The function returns the handle of the Awesome oscillator indicator. It has only one buffer.
int iAO(
string symbol, // symbol name
ENUM_TIMEFRAMES period // period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iATR
The function returns the handle of the Average True Range indicator. It has only one buffer.
int iATR(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] The value of the averaging period for the indicator calculation.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iBearsPower
The function returns the handle of the Bears Power indicator. It has only one buffer.
int iBearsPower(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] The value of the averaging period for the indicator calculation.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iBands
The function returns the handle of the Bollinger Bands indicator.
int iBands(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int bands_period, // period for average line calculation
int bands_shift, // horizontal shift of the indicator
double deviation, // number of standard deviations
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
bands_period
[in] The averaging period of the main line of the indicator.
bands_shift
[in] The shift the indicator relative to the price chart. It should be remembered that the line shift
is only visual, and values in the indicator buffer are stored without the shift. When obtaining
buffer values using the CopyBuffer() function,the shift value will have no effect.
deviation
[in] Deviation from the main line.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iBullsPower
The function returns the handle of the Bulls Power indicator. It has only one buffer.
int iBullsPower(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] The averaging period for the indicator calculation.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iCCI
The function returns the handle of the Commodity Channel Index indicator. It has only one buffer.
int iCCI(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] The averaging period for the indicator calculation.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iChaikin
The function returns the handle of the Chaikin Oscillator indicator. It has only one buffer.
int iChaikin(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int fast_ma_period, // fast period
int slow_ma_period, // slow period
ENUM_MA_METHOD ma_method, // smoothing type
ENUM_APPLIED_VOLUME applied_price // type of volume
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
fast_ma_period
[in] Fast averaging period for calculations.
slow_ma_period
[in] Slow averaging period for calculations.
ma_method
[in] Smoothing type. Can be one of the averaging constants of ENUM_MA_METHOD.
applied_volume
[in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iCustom
The function returns the handle of a specified custom indicator.
int iCustom(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
string name // folder/custom indicator_name
... // list of indicator input parameters
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
name
[in] The name of the custom indicator, with path relative to the root directory of indicators
(MQL5/Indicators/). If an indicator is located in a subdirectory, for example, in MQL5/Indicators/
Examples, its name must be specified like: "Examples\\indicator_name" (it is necessary to use a
double slash instead of the single slash as a separator).
...
[in] input-parameters of a custom indicator, separated by commas. Type and order of parameters
must match. If there is no parameters specified, then default values will be used.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
A custom indicator must be compiled (with extension EX5) and located in the directory MQL5/
Indicators of the client terminal or its subdirectory.
Indicators that require testing are defined automatically from the call of the iCustom() function, if
the corresponding parameter is set through a constant string. For all other cases (use of the
IndicatorCreate() function or use of a non-constant string in the parameter that sets the indicator
name) the property #property tester_indicator is required:
If the first call form is used in the indicator, then at the custom indicator start you can additionally
indicate data for calculation in its "Parameters" tab. If the "Apply to" parameter is not selected
explicitly, the default calculation is based on the values of "Close" prices.
When you call a custom indicator from mql5-program, the Applied_Price parameter or a handle of
another indicator should be passed last, after all input variables of the custom indicator.
See also
Program Properties, Timeseries and Indicators Access,IndicatorCreate(), IndicatorRelease()
Example:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int MA_Period=21;
input int MA_Shift=0;
input ENUM_MA_METHOD MA_Method=MODE_SMA;
//--- indicator buffers
double Label1Buffer[];
//--- Handle of the Custom Moving Average.mq5 custom indicator
int MA_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
ResetLastError();
MA_handle=iCustom(NULL,0,"Custom Moving Average",
MA_Period,
MA_Shift,
MA_Method,
PRICE_CLOSE // using the close prices
);
Print("MA_handle = ",MA_handle," error = ",GetLastError());
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- Copy the values of the indicator Custom Moving Average to our indicator buffer
int copy=CopyBuffer(MA_handle,0,0,rates_total,Label1Buffer);
Print("copy = ",copy," rates_total = ",rates_total);
//--- If our attempt has failed - Report this
if(copy<=0)
Print("An attempt to get the values if Custom Moving Average has failed");
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
iDEMA
The function returns the handle of the Double Exponential Moving Average indicator. It has only one
buffer.
int iDEMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
int ma_shift, // horizontal shift
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period (bars count) for calculations.
ma_shift
[in] Shift of the indicator relative to the price chart.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iDeMarker
The function returns the handle of the DeMarker indicator. It has only one buffer.
int iDeMarker(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period (bars count) for calculations.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iEnvelopes
The function returns the handle of the Envelopes indicator.
int iEnvelopes(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // period for the average line calculation
int ma_shift, // horizontal shift of the indicator
ENUM_MA_METHOD ma_method, // type of smoothing
ENUM_APPLIED_PRICE applied_price, // type of price or handle
double deviation // deviation of boundaries from the midline (in percents)
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the main line.
ma_shift
[in] The shift of the indicator relative to the price chart. It should be remembered that the line
shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining
buffer values using the CopyBuffer() function,the shift value will have no effect.
ma_method
[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
deviation
[in] The deviation from the main line (in percents).
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iForce
The function returns the handle of the Force Index indicator. It has only one buffer.
int iForce(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
ENUM_MA_METHOD ma_method, // smoothing type
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the indicator calculations.
ma_method
[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.
applied_volume
[in] The volume used. Can be one of the values of ENUM_APPLIED_VOLUME.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iFractals
The function returns the handle of the Fractals indicator.
int iFractals(
string symbol, // symbol name
ENUM_TIMEFRAMES period // period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iFrAMA
The function returns the handle of the Fractal Adaptive Moving Average indicator. It has only one
buffer.
int iFrAMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
int ma_shift, // horizontal shift on the chart
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Period (bars count) for the indicator calculations.
ma_shift
[in] Shift of the indicator in the price chart.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iGator
The function returns the handle of the Gator indicator. The Oscillator shows the difference between
the blue and red lines of Alligator (upper histogram) and difference between red and green lines (lower
histogram).
int iGator(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int jaw_period, // period for the calculation of the jaws
int jaw_shift, // jaws horizontal shift
int teeth_period, // period for the calculation of the teeth
int teeth_shift, // teeth horizontal shift
int lips_period, // period for the calculation of the lips
int lips_shift, // lips horizontal shift
ENUM_MA_METHOD ma_method, // type of smoothing
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
jaw_period
[in] Averaging period for the blue line (Alligator's Jaw).
jaw_shift
[in] The shift of the blue line relative to the price chart. It isn't directly connected with the visual
shift of the indicator histogram.
teeth_period
[in] Averaging period for the red line (Alligator's Teeth).
teeth_shift
[in] The shift of the red line relative to the price chart. It isn't directly connected with the visual
shift of the indicator histogram.
lips_period
[in] Averaging period for the green line (Alligator's lips).
lips_shift
[in] The shift of the green line relative to the price charts. It isn't directly connected with the
visual shift of the indicator histogram.
ma_method
[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iIchimoku
The function returns the handle of the Ichimoku Kinko Hyo indicator.
int iIchimoku(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int tenkan_sen, // period of Tenkan-sen
int kijun_sen, // period of Kijun-sen
int senkou_span_b // period of Senkou Span B
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
tenkan_sen
[in] Averaging period for Tenkan Sen.
kijun_sen
[in] Averaging period for Kijun Sen.
senkou_span_b
[in] Averaging period for Senkou Span B.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iBWMFI
The function returns the handle of the Market Facilitation Index indicator. It has only one buffer.
int iBWMFI(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
applied_volume
[in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iMomentum
The function returns the handle of the Momentum indicator. It has only one buffer.
int iMomentum(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int mom_period, // averaging period
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
mom_period
[in] Averaging period (bars count) for the calculation of the price change.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iMFI
The function returns the handle of the Money Flow Index indicator.
int iMFI(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period (bars count) for the calculation.
applied_volume
[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iMA
The function returns the handle of the Moving Average indicator. It has only one buffer.
int iMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
int ma_shift, // horizontal shift
ENUM_MA_METHOD ma_method, // smoothing type
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the calculation of the moving average.
ma_shift
[in] Shift of the indicator relative to the price chart.
ma_method
[in] Smoothing type. Can be one of the ENUM_MA_METHOD values.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iOsMA
The function returns the handle of the Moving Average of Oscillator indicator. The OsMA oscillator
shows the difference between values of MACD and its signal line. It has only one buffer.
int iOsMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int fast_ema_period, // period for Fast Moving Average
int slow_ema_period, // period for Slow Moving Average
int signal_period, // averaging period for their difference
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
fast_ema_period
[in] Period for Fast Moving Average calculation.
slow_ema_period
[in] Period for Slow Moving Average calculation.
signal_period
[in] Averaging period for signal line calculation.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iMACD
The function returns the handle of the Moving Averages Convergence/Divergence indicator. In
systems where ОsМА is called MACD Histogram, this indicator is shown as two lines. In the client
terminal the Moving Averages Convergence/Divergence looks like a histogram.
int iMACD(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int fast_ema_period, // period for Fast average calculation
int slow_ema_period, // period for Slow average calculation
int signal_period, // period for their difference averaging
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
fast_ema_period
[in] Period for Fast Moving Average calculation.
slow_ema_period
[in] Period for Slow Moving Average calculation.
signal_period
[in] Period for Signal line calculation.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iOBV
The function returns the handle of the On Balance Volume indicator. It has only one buffer.
int iOBV(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
applied_volume
[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iSAR
The function returns the handle of the Parabolic Stop and Reverse system indicator. It has only one
buffer.
int iSAR(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
double step, // step increment
double maximum // maximal stop level
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
step
[in] The stop level increment, usually 0.02.
maximum
[in] The maximal stop level, usually 0.2.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iRSI
The function returns the handle of the Relative Strength Index indicator. It has only one buffer.
int iRSI(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the RSI calculation.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iRVI
The function returns the handle of the Relative Vigor Index indicator.
int iRVI(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the RVI calculation.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iStdDev
The function returns the handle of the Standard Deviation indicator. It has only one buffer.
int iStdDev(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
int ma_shift, // horizontal shift
ENUM_MA_METHOD ma_method, // smoothing type
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period for the indicator calculations.
ma_shift
[in] Shift of the indicator relative to the price chart.
ma_method
[in] Type of averaging. Can be any of the ENUM_MA_METHOD values.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iStochastic
The function returns the handle of the Stochastic Oscillator indicator.
int iStochastic(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int Kperiod, // K-period (number of bars for calculations)
int Dperiod, // D-period (period of first smoothing)
int slowing, // final smoothing
ENUM_MA_METHOD ma_method, // type of smoothing
ENUM_STO_PRICE price_field // stochastic calculation method
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
Kperiod
[in] Averaging period (bars count) for the %K line calculation.
Dperiod
[in] Averaging period (bars count) for the %D line calculation.
slowing
[in] Slowing value.
ma_method
[in] Type of averaging. Can be any of the ENUM_MA_METHOD values.
price_field
[in] Parameter of price selection for calculations. Can be one of the ENUM_STO_PRICE values.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Note
iTEMA
The function returns the handle of the Triple Exponential Moving Average indicator. It has only one
buffer.
int iTEMA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
int ma_shift, // horizontal shift of indicator
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period (bars count) for calculation.
ma_shift
[in] Shift of indicator relative to the price chart.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iTriX
The function returns the handle of the Triple Exponential Moving Averages Oscillator indicator. It has
only one buffer.
int iTriX(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int ma_period, // averaging period
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
ma_period
[in] Averaging period (bars count) for calculations.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iWPR
The function returns the handle of the Larry Williams' Percent Range indicator. It has only one buffer.
int iWPR(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int calc_period // averaging period
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
calc_period
[in] Period (bars count) for the indicator calculation.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iVIDyA
The function returns the handle of the Variable Index Dynamic Average indicator. It has only one
buffer.
int iVIDyA(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
int cmo_period, // period for Chande Momentum
int ema_period, // EMA smoothing period
int ma_shift, // horizontal shift on the price chart
ENUM_APPLIED_PRICE applied_price // type of price or handle
);
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
cmo_period
[in] Period (bars count) for the Chande Momentum Oscillator calculation.
ema_period
[in] EMA period (bars count) for smoothing factor calculation.
ma_shift
[in] Shift of the indicator relative to the price chart.
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
iVolumes
The function returns the handle of the Volumes indicator. It has an only one buffer.
int iVolumes(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ENUM_APPLIED_VOLUME applied_volume // volume type for calculation
)
Parameters
symbol
[in] The symbol name of the security, the data of which should be used to calculate the indicator.
The NULL value means the current symbol.
period
[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current
timeframe.
applied_volume
[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.
Returned value
Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
The computer memory can be freed from an indicator that is no more utilized, using the
IndicatorRelease() function, to which the indicator handle is passed.
Event Functions
This group contains functions for working with custom events and timer events. Besides this group,
there are special functions for handling predefined events.
Function Action
See also
Types of Chart Events
EventSetTimer
The function indicates to the client terminal, that events from the timer must be generated with the
specified periodicity for the chart, to which the Expert Advisor is attached.
bool EventSetTimer(
int seconds // number of seconds
);
Parameters
seconds
[in] Number of seconds that determine the frequency of the timer event occurrence.
Return Value
In case of success returns true, otherwise false. In order to get an error code, the GetLastError()
function should be called.
Note
Normally, this function must be called from the OnInit() function or from a class constructor. In
order to handle events coming from the timer, the Expert Advisor must have the OnTimer()
function.
Every Expert Advisor, as well as every indicator works with its own timer and receives events only
from it. As soon as a mql5 program stops operating, the timer is destroyed forcibly if it was created
but hasn't been disabled by the EventKillTimer() function.
EventKillTimer
Specifies the client terminal that is necessary to stop the generation of events from Timer.
void EventKillTimer();
Return Value
No return value.
Note
Typically, this function must be called from a function OnDeinit(), if the EventSetTimer() function
has been called from OnInit(). This function can also be called form the class destructor, if the
EventSetTimer() function has been called in the constructor of this class.
Every Expert Advisor, as well as every indicator works with its own timer and receives events only
from it. As soon as a mql5 program stops operating, the timer is destroyed forcibly if it was created
but hasn't been disabled by the EventKillTimer() function
EventChartCustom
The function generates a custom event for the specified chart.
bool EventChartCustom(
long chart_id, // identifier of the event receiving chart
ushort custom_event_id, // event identifier
long lparam, // parameter of type long
double dparam, // parameter of type double
string sparam // string parameter of the event
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
custom_event_id
[in] ID of the user events. This identifier is automatically added to the value
CHARTEVENT_CUSTOM and converted to the integer type.
lparam
[in] Event parameter of the long type passed to the OnChartEvent function.
dparam
[in] Event parameter of the double type passed to the OnChartEvent function.
sparam
[in] Event parameter of the string type passed to the OnChartEvent function. If the string is
longer than 63 characters, it is truncated.
Return Value
The function returns true in case a custom event has been successfully placed to the queue of
messages. In case of failure, it returns false. Use GetLastError() to get an error code.
Note
An Expert Advisor or indicator attached to the specified chart handles the event using the function
OnChartEvent(int event_id, long& lparam, double& dparam, string& sparam).
For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through this parameters
are listed in the below table.
ID of the user CHARTEVENT_CU Value set by the Value set by the Value set by the
event under the STOM+N EventChartCusto EventChartCusto EventChartCusto
N number m() fubction m() function m() function
Example:
//+------------------------------------------------------------------+
//| ButtonClickExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
string buttonID="Button";
string labelID="Info";
int broadcastEventID=5000;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Create a button to send custom events
ObjectCreate(0,buttonID,OBJ_BUTTON,0,100,100);
ObjectSetInteger(0,buttonID,OBJPROP_COLOR,clrWhite);
ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,clrGray);
ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,200);
ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,50);
ObjectSetString(0,buttonID,OBJPROP_FONT,"Arial");
ObjectSetString(0,buttonID,OBJPROP_TEXT,"Button");
ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,10);
ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);
//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ObjectDelete(0,buttonID);
ObjectDelete(0,labelID);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Check the event by pressing a mouse button
if(id==CHARTEVENT_OBJECT_CLICK)
{
string clickedChartObject=sparam;
//--- If you click on the object with the name buttonID
if(clickedChartObject==buttonID)
{
//--- State of the button - pressed or not
bool selected=ObjectGetInteger(0,buttonID,OBJPROP_STATE);
//--- log a debug message
Print("Button pressed = ",selected);
int customEventID; // Number of the custom event to send
string message; // Message to be sent in the event
//--- If the button is pressed
if(selected)
{
message="Button pressed";
customEventID=CHARTEVENT_CUSTOM+1;
}
else // Button is not pressed
{
message="Button in not pressed";
customEventID=CHARTEVENT_CUSTOM+999;
}
//--- Send a custom event "our" chart
EventChartCustom(0,customEventID-CHARTEVENT_CUSTOM,0,0,message);
///--- Send a message to all open charts
BroadcastEvent(ChartID(),0,"Broadcast Message");
//--- Debug message
Print("Sent an event with ID = ",customEventID);
}
ChartRedraw();// Forced redraw all chart objects
}
else
{
//--- We read a text message in the event
string info=sparam;
Print("Handle the user event with the ID = ",id);
//--- Display a message in a label
ObjectSetString(0,labelID,OBJPROP_TEXT,sparam);
ChartRedraw();// Forced redraw all chart objects
}
}
}
//+------------------------------------------------------------------+
//| sends broadcast event to all open charts |
//+------------------------------------------------------------------+
void BroadcastEvent(long lparam,double dparam,string sparam)
{
int eventID=broadcastEventID-CHARTEVENT_CUSTOM;
long currChart=ChartFirst();
int i=0;
while(i<CHARTS_MAX // We have certainly no more than CHARTS_MAX open charts
{
EventChartCustom(currChart,eventID,lparam,dparam,sparam);
currChart=ChartNext(currChart); // We have received a new chart from the previous
if(currChart==0) break; // Reached the end of the charts list
i++;// Do not forget to increase the counter
}
}
//+------------------------------------------------------------------+
See also
Events of the client terminal, Event handler functions
Standard Library
This group of chapters contains the technical details of the MQL5 Standard Library and descriptions of
all its key components.
MQL5 Standard Library is written in MQL5 and is designed to facilitate writing programs (indicators,
scripts, experts) to end users. Library provides convenient access to most of the internal functions
MQL5.
MQL5 Standard Library is placed in the working directory of the terminal in the 'Include' folder.
Section Location
Description
Class CObject provides all its descendants to be part of a linked list. Also identifies a number of
virtual methods for further implementation in descendant classes.
Declaration
class CObject
Title
#include <Object.mqh>
Class Methods
Attributes
Compare methods
Input/output
Derived classes:
CArray
CChartObject
CChart
CString
CFile
CList
CTreeNode
Prev
Gets a pointer to the previous list item.
CObject* Prev()
Return Value
Pointer to the previous list item. If an item is listed first, then return NULL.
Example:
Prev
Sets the pointer to the previous list item.
void Prev(
CObject* object // Pointer to the previous list item
)
Parameters
object
[in] New value pointer to the previous list item.
Example:
Next
Gets a pointer to the next element of the list.
CObject* Next()
Return Value
Pointer to the next item in the list. If the last item in the list, returns NULL.
Example:
Next
Sets the pointer to the next element of the list.
void Next(
CObject* object // Pointer to the next list item
)
Parameters
object
[in] New value pointer to the next list item.
Example:
Compare
Compares the data item in the list with data on another element of the list.
Parameters
node
[in] Pointer to a list item to compare
mode=0
[in] Variant Comparison
Return Value
0 - in case the list items are equal, -1 - if the list item is less than the item in the list for
comparison (node), 1 - if the list item more than item in the list for comparison (node).
Note
Method Compare () in class CObject always returns 0 and does not perform any action.If you want to
compare data derived class, the method Compare (...) Should be implemented.The mode parameter
should be used when implementing multivariate comparison.
Example:
object_second.Prev(object_first);
//--- compare objects
int result=object_first.Compare(object_second);
//--- delete objects
delete object_first;
delete object_second;
}
Save
Saves data element list in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (), binary
Return Value
Note
Method Save (int) in class CObject always returns true and does not perform any action. If you want
to save the data derived class in the file, the method Save (int) should be implemented.
Example:
FileClose(file_handle);
}
delete object;
}
Load
Loads data item in the list from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (), binary
Return Value
Note
Method Load (int) in class CObject always returns true and does not perform any action. If you want
to load the data derived class from a file, the method Load (int) should be implemented.
Example:
Type
Gets the type identifier.
Return Value
Example:
Data Structures
This section contains the technical details of working with various data structures (arrays, linked lists,
etc.) and description of the relevant components of the MQL5 Standard Library .
Using classes of data structures, will save time when creating custom data stores of various formats
(including composite data structures).
MQL5 Standard Library (in terms of data sets) is placed in the working directory of the terminal in the
Include\Arrays folder.
Data Arrays
Use of classes of dynamic arrays of data will save time when creating a custom data stores of various
formats (including multidimensional arrays).
MQL5 Standard Library (in terms of arrays of data) is placed in the working directory of the terminal
in the Include\Arrays folder.
Class Description
Base class of dynamic data array CArray Base class of dynamic data array
Base class of list CList Provides the ability to work with a list of
instances of CObject and its descendant
CArray
CArray class is the base class a dynamic array of variables.
Description
Class CArray provides the ability to work with a dynamic array of variables in the part of the attributes
of management of memory allocation, sorting, and working with files.
Declaration
class CArray : public CObject
Title
#include <Arrays\Array.mqh>
Class Methods
Attributes
Clear methods
Sort methods
Input/output
Derived classes:
CArrayChar
CArrayShort
CArrayInt
CArrayLong
CArrayFloat
CArrayDouble
CArrayString
CArrayObj
Step
Gets the step increment size of the array.
Return Value
Example:
Step
Sets the increment size of the array.
bool Step(
int step // step
)
Parameters
step
[in] The new value of step increments in the size of the array.
Return Value
true if successful, false - if there was an attempt to establish a step less than or equal to zero.
Example:
Total
Gets the number of elements in the array.
Return Value
Example:
Available
Gets the number of free elements of the array are available without additional memory allocation.
Return Value
Number of free elements of the array are available without additional memory allocation.
Example:
Max
Gets the maximum possible size of the array without memory reallocation.
Return Value
Example:
IsSorted
Gets sign sorted array to the specified option.
bool IsSorted(
int mode=0 // Sorting mode
) const
Parameters
mode=0
[in] Tested version of the sort.
Return Value
Flag of the sorted list. If the list is sorted by the specified version - true, otherwise - false.
Note
Symptom sorted array can not be changed directly. Symptom sorted set method Sort () and reset
any methods to add / insert except InsertSort (...).
Example:
SortMode
Gets the version of the sorting array.
Return Value
Sorting mode.
Example:
Clear
Deletes all of the array elements without memory release.
void Clear()
Return Value
None.
Example:
Sort
Sorts an array to the specified option.
void Sort(
int mode=0 // Sorting mode
)
Parameters
mode=0
[in] Mode of array sorting.
Return Value
No.
Note
Sorting an array is always ascending.For arrays of primitive data types (CArrayChar, CArrayShort,
etc.), the parameter mode is not used.For the array CArrayObj, multivariate sort should be
implemented in the method Sort (int) derived class.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
CArrayChar
CArrayChar class is a class of dynamic array of variables of type char or uchar.
Description
Class CArrayChar provides the ability to work with a dynamic array of variables of type char or uchar.
In the class implemented the ability to add / insert / delete elements in an array, sort array,
searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayChar : public CArray
Title
#include <Arrays\ArrayChar.mqh>
Class Methods
Memory control
Add methods
Modify methods
Delete methods
Access methods
Compare methods
Input/output
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
char element // Element to add
)
Parameters
element
[in] value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const char& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayChar* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayChar-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
char element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray(
const char& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray(
CArrayChar* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayChar-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const char& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayChar* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayChar-source element to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
char element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Value
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] Position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Positions of the last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
char At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, CHAR_MAX-if there was an attempt to get an element
of not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, CHAR_MAX may be a valid value of an array element, so having a value, always check the
last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const char& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const CArrayChar* src // Pointer to the sources
) const
Parameters
src
[in] Pointer to an instance of class CArrayChar-source elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
char element // Element to insert
)
Parameters
element
[in] Value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array
int SearchGreatOrEqual(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
char element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
//--- delete array
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayShort
CArrayShort class is a class of dynamic array of variables of type short or ushort.
Description
Class CArrayShort provides the ability to work with a dynamic array of variables of type short or
ushort.In the class implemented the ability to add / insert / delete elements in an array, sort array,
searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayShort : public CArray
Title
#include <Arrays\ArrayShort.mqh>
Class Methods
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
short element // Element to add
)
Parameters
element
[in] Value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const short& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayShort* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayShort-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
short element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
const short& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray(
CArrayShort* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayShort-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const short& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayShort* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayShort-source element to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
short element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Positions
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] Position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of the lase element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
short At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, SHORT_MAX-if there was an attempt to get an element
of not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, SHORT_MAX may be a valid value of an array element, so having a value, always check
the last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const short& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const CArrayShort* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayShort-source elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
short element // Element to insert
)
Parameters
element
[in] Value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
short element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayInt
CArrayInt class is a class of dynamic array of variables of type int or uint.
Description
Class CArrayInt provides the ability to work with a dynamic array of variables of type int or uint.In the
class implemented the ability to add / insert / delete elements in an array, sort array, searching in
sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayInt : public CArray
Title
#include <Arrays\ArrayInt.mqh>
Class Methods
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Number
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
int element // Element to add
)
Parameters
element
[in] value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const int& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayInt* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayInt-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
int element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
const int& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
CArrayInt* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayInt-source elements to insert.
pos
[in] Position in the array to insert.
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const int& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayInt* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayInt-source element to copy.
Return Value
Example:
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
int element // Value
)
Parameters
pos
[in] Position of the element in the array to change.
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] Position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of the last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
int At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, INT_MAX-if there was an attempt to get an element of
not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, INT_MAX could be a valid value of an array element, so having a value, always check the
last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const int& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const CArrayInt* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayInt-source elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
int element // Element to insert
)
Parameters
element
[in] value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
int element // Element to search
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
int element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayLong
CArrayLong class is a class of dynamic array of variables of type long or ulong.
Description
Class CArrayLong provides the ability to work with a dynamic array of variables of type long or ulong.
In the class implemented the ability to add / insert / delete elements in an array, sort array,
searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayLong : public CArray
Title
#include <Arrays\ArrayLong.mqh>
Class Methods
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
long element // Element to add
)
Parameters
element
[in] Value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const long& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayLong* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayLong-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
long element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray(
const long& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray(
CArrayLong* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayLong-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const long& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayLong* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayLong-source element to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
long element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] Position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of the last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
long At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, LONG_MAX if there was an attempt to get an element
of not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, LONG_MAX may be a valid value of an array element, so having a value, always check the
last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const long& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArrayconst
Compares array with another array.
bool CompareArrayconst(
const CArrayLong* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayLong-source elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
long element // Element to insert
)
Parameters
element
[in] Value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the model in sorted array.
int Search(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of larger sample, in sorted array.
int SearchGreat(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the model in sorted array.
int SearchGreatOrEqual(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the model in sorted array.
int SearchLessOrEqual(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the model in sorted array.
int SearchFirst(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
long element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayFloat
CArrayFloat class is a class of dynamic array of variables of type float.
Description
Class CArrayFloat provides the ability to work with a dynamic array of variables of type float.In the
class implemented the ability to add / insert / delete elements in an array, sort array, searching in
sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayFloat : public CArray
Title
#include <Arrays\ArrayFloat.mqh>
Class Methods
Attributes
Memory control
Add methods
Update methods
Access methods
Compare methods
Input/output
Delta
Set tolerance comparison.
void Delta(
float delta // Tolerance
)
Parameters
delta
[in] the new value of the admission of comparison.
Return Value
None
Note
Admission of comparison used in the search. Values are considered equal if their difference is less
than or equal to tolerance. The default tolerance is 0.0.
Example:
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
float element // Element to add
)
Parameters
element
[in] Value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const float& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayFloat* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayFloat-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
float element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray(
const float& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
CArrayFloat* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayFloat-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const float& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayFloat* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayFloat-source element to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
float element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] Position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
float At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, FLT_MAX if there was an attempt to get an element of
not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, FLT_MAX may be a valid value of an array element, so having a value, always check the
last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const float& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
AssignArrayconst
Copies the array elements from another array.
bool AssignArrayconst(
const CArrayFloat* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayFloat-source element to copy.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
float element // Element to insert
)
Parameters
element
[in] Value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
float element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayDouble
CArrayDouble class is a class of dynamic array of variables of type double.
Description
Class CArrayDouble provides the ability to work with a dynamic array of variables of type double.In the
class implemented the ability to add / insert / delete elements in an array, sort array, searching in
sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayDouble : public CArray
Title
#include <Arrays\ArrayDouble.mqh>
Class Methods
Attributes
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Derived classes:
CIndicatorBuffer
Delta
Set tolerance comparison.
void Delta(
double delta // Tolerance
)
Parameters
delta
[in] The new value of the admission of comparison.
Return Value
No
Note
Admission of comparison used in the search. Values are considered equal if their difference is less
than or equal to tolerance. The default tolerance is 0.0.
Example:
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
double element // Element to add
)
Parameters
element
[in] value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const double& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayDouble* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayDouble-source elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
double element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
const double& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
CArrayDouble* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayDouble-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const double& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayDouble* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayDouble-source element to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
double element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value.
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
double At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, DBL_MAX if there was an attempt to get an element of
not existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, DBL_MAX may be a valid value of an array element, so having a value, always check the
last error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const double& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const CArrayDouble* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayDouble-source elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
double element // Element to insert
)
Parameters
element
[in] value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
double element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
//--- delete array
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
//--- delete array
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayString
CArrayString class is a class of dynamic array of variables of type string.
Description
Class CArrayString provides the ability to work with a dynamic array of variables of type string.In the
class implemented the ability to add / insert / delete elements in an array, sort array, searching in
sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayString : public CArray
Title
#include <Arrays\ArrayString.mqh>
Class Methods
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
true if successful, false - if there was an attempt to set the size of less than or equal to zero.
Note
Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
Example:
Add
Adds an element to the end of the array.
bool Add(
string element // Element to add
)
Parameters
element
[in] value of the element to add to the array.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const string& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayString* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayString - the source of elements to add.
Return Value
Example:
Insert
Inserts an element in the array to the specified position.
bool Insert(
string element, // Element to insert
int pos // Position
)
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
const string& src[], // Source array
int pos // Position
)
Parameters
src[]
[in] Reference to an array of source elements to insert
pos
[in] Position in the array to insert
Return Value
Example:
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
CArrayString* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayString - the source of elements to insert.
pos
[in] Position in the array to insert
Return Value
Example:
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const string& src[] // Source array
)
Parameters
src[]
[in] Reference to an array of source elements to copy.
Return Value
Example:
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayString* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayString - source of elements to copy.
Return Value
Example:
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
string element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] position removes the element in the array.
Return Value
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Example:
At
Gets the element from the given position in the array.
string At(
int pos // Position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element in case of success, "- if there was an attempt to get an element of not
existing positions (the last error ERR_OUT_OF_RANGE).
Note
Of course, "" may be a valid value of an array element, so having a value, always check the last
error code.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const string& src[] // Source array
) const
Parameters
src[]
[in] Reference to an array of source elements for comparison.
Return Value
Example:
CompareArray
Compares array with another array.
bool CompareArrays(
const CArrayString* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayString - the source of elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
string element // Element to insert
)
Parameters
element
[in] value of the element to be inserted into a sorted array
Return Value
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
string element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Load
Loads data array from a file.
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Example:
}
delete array;
}
Type
Gets the type identifier of the array.
Return Value
Example:
CArrayObj
CArrayObj class is a class of dynamic array of pointers to instances of CObject and his heirs.
Description
Class CArrayObj provides the ability to work with a dynamic array of pointers to instances of CObject
and his heirs. This gives the possibility to work as a multidimensional dynamic arrays of primitive
data types, and the more difficult for organized data structures.
In the class implemented the ability to add / insert / delete elements in an array, sort array,
searching in sorted array. In addition, the implemented methods of work with the file.
Declaration
class CArrayObj : public CArray
Title
#include <Arrays\ArrayObj.mqh>
Class Method
Attributes
Memory control
Add methods
Update methods
Delete methods
Access methods
Compare methods
Input/output
Derived classes:
CIndicator
CIndicators
Practical application of arrays are descendants of class CObject (including all classes of the standard
library).
#include <Arrays\ArrayDouble.mqh>
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
int i,j;
int first_size=10;
int second_size=100;
//--- create array
CArrayObj *array=new CArrayObj;
CArrayDouble *sub_array;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create subarrays
for(i=0;i<first_size;i++)
{
sub_array=new CArrayDouble;
if(sub_array==NULL)
{
delete array;
printf("Object create error");
return;
}
//--- fill array
for(j=0;j<second_size;j++)
{
sub_array.Add(i*j);
}
array.Add(sub_array);
}
//--- create array OK
for(i=0;i<first_size;i++)
{
sub_array=array.At(i);
for(j=0;j<second_size;j++)
{
double element=sub_array.At(j);
//--- use array element
}
}
delete array;
}
Subtleties
The class has a mechanism to control dynamic memory, so be careful when working with elements of
the array.
Mechanism of memory management can be switched on / off using the method FreeMode (bool). By
default, the mechanism is enabled.
Accordingly, there are two options for dealing with the class CArrayObj:
In this case, CArrayObj take responsibility for freeing the memory elements after their removal from
the array. In this program the user should not free the array elements.
Example:
int i;
//--- Create an array
CArrayObj *array=new CArrayObj;
//--- Fill array elements
for(i=0;i<10;i++) array.Add(new CObject);
//--- Do something
for(i=0;i<array.Total();i++)
{
CObject *object=array.At(i);
//--- Action with an element
. . .
}
//--- Remove the array with the elements
delete array;
In this case, CArrayObj not otvetstvechaet for freeing the memory elements after their removal from
the array. In this program the user must free the array elements.
Example:
int i;
FreeMode
Gets the flag memory management.
Return Value
Example:
FreeMode
Sets the flag memory management.
void FreeMode(
bool mode // New flag
)
Parameters
mode
[in] New value of the flag memory management.
Return Value
None.
Note
Setting the flag memory management - an important point in the use of class CArrayObj.Since the
array elements are pointers to dynamic objects, it is important to determine what to do with them
when removing from the array.
If the flag is set, removing an element from the array, the element is automatically deleted by the
operator delete.If the flag is not set, it is assumed that a pointer to the deleted object is still
somewhere in the user program and will be relieved of it (the program) then.
If the user resets the flag memory management, the user must understand their responsibility for
the removal of the array before the completion of the program, because otherwise, is not freed
memory occupied by the elements when they create new operator.
When large amounts of data, it could lead, eventually, even to break your terminal.If the user does
not reset the flag memory management, there is another "reef".
Using pointers, array, stored somewhere in the local variables, after removing the array will lead to
a critical error and crashes the program user.By default, the memory management flag is set, ie the
class of the array is responsible for freeing the memory elements.
Example:
Reserve
Allocates memory to increase the size of the array.
bool Reserve(
int size // Number
)
Parameters
size
[in] The number of additional elements of the array.
Return Value
true if successful, false - if there was an attempt to seek the amount is less than or equal to zero,
or if the array did not increase.
Note
To reduce memory fragmentation, increase the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Resize
Sets a new (smaller) size of the array.
bool Resize(
int size // Size
)
Parameters
size
[in] New size of the array.
Return Value
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Note
Changing the size of array allows to use memory in the optimal way. Excess element located to the
right are lost. The memory for lost elements is released or not depending on the mode of memory
management.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
Clear
Removes all elements of the array without the release of the memory array.
void Clear()
Return Value
No.
Note
Example:
Shutdown
Clears the array with a total exemption memory array (not element).
bool Shutdown()
Return Value
Note
Example:
CreateElement
Creates a new array element at the specified position.
bool CreateElement(
int index // Position
)
Parameters
index
[in] position in which you want to create a new element.
Return Value
Note
Method CreateElement (int) in class CArrayObj always returns false and does not perform any
action. If necessary, in a derived class, method CreateElement (int) should be implemented.
Example:
Add
Adds an element to the end of the array.
bool Add(
CObject* element // Element to add
)
Parameters
element
[in] value of the element to add to the array.
Return Value
Note
Element is not added to the array if the value for transmit invalid pointer (such as NULL).
Example:
AddArray
Adds to the end of the array elements from another array.
bool AddArray(
const CArrayObj * src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayDouble - source of elements to add.
Return Value
Note
Adding elements of the array in the array is actually copying the pointers.Therefore, when calling
the method, there is a "reef" - that there may be a pointer to a dynamic object in more than one
variable.
//--- example
extern bool make_error;
extern int error;
extern CArrayObj *src;
//--- Create a new instance CArrayObj
//--- Default memory management is turned on
CArrayObj *array=new CArrayObj;
//--- Add (copy) the elements of the array-istochika
if(array!=NULL)
bool result=array.AddArray(src);
if(make_error)
{
//--- Commit wrongdoing
switch(error)
{
case 0:
//--- Remove the array-source, without checking its flag memory management
delete src;
//--- Result:
//--- May appeal
//--- For "bitomu" pointer in the array receiver
break;
case 1:
//--- Disable the mechanism of memory management in an array of source
if(src.FreeMode()) src.FreeMode(false);
//--- But do not remove the array-source
//--- Result:
//--- After removal of the array, the receiver may appeal
Example:
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
Insert
Inserts an element in the array to the specified position.
bool Insert(
CObject* element, // Element to insert
int pos // Position
)
Parameters
element
[in] value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
Note
Element is not added to the array if the value for transmit invalid pointer (such as NULL).
Example:
delete array;
}
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray(
const CArrayObj* src, // Pointer to the source
int pos // Position
)
Parameters
src
[in] Pointer to an instance of class CArrayObj-source elements to insert.
pos
[in] Position in the array to insert
Return Value
Note
Example:
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
AssignArray
Copies the array elements from another array.
bool AssignArray(
const CArrayObj* src // Pointer to the source
)
Parameters
src
[in] Pointer to an instance of class CArrayObj - source of elements to copy.
Return Value
Note
If the challenge AssignArray array receiver is not empty, all its elements will be removed from the
array and, if the flag memory management, memory, deleted items will be released.Array-receiver
is an exact copy of the array source. Additionally see CArrayObj::AddArray(const CArrayObj*).
Example:
Update
Changes the element at the specified position array.
bool Update(
int pos, // Position
CObject* element // Value
)
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value element
Return Value
Note
The element does not change if we as a parameter to pass an invalid pointer (ie NULL). If enabled
memory management, memory placeholder released.
Example:
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift(
int pos, // Position
int shift // Shift
)
Parameters
pos
[in] Position of the moved element array
shift
[in] The value of displacement (both positive and negative).
Return Value
Example:
Detach
Remove an item from a given position in the array.
CObject* Detach(
int pos // Position
)
Parameters
pos
[in] Position of the seized item in the array.
Return Value
Pointer to the removal of elements in case of success, NULL - if you can not remove the element.
Note
When removed from the array element is not removed in any state of the flag memory
management. Pointer to the array element withdrawn from the ingredients of the release after use.
Example:
Delete
Removes the element from the given position in the array.
bool Delete(
int pos // Position
)
Parameters
pos
[in] position removes the element in the array.
Return Value
Note
Example:
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)
Parameters
from
[in] Position of the first removes the element in the array.
to
[in] Position of the last deleted element in the array.
Return Value
Note
Example:
At
Gets the element from the given position in the array.
CObject* At(
int pos // Position
)
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element, if successful, NULL-if there was an attempt to get an element of non-
existent position.
Example:
CompareArray
Compares array with another array.
bool CompareArray(
const CArrayObj* src // Pointer to the source
) const
Parameters
src
[in] Pointer to an instance of class CArrayObj - the source of elements for comparison.
Return Value
Example:
InsertSort
Inserts element in a sorted array.
bool InsertSort(
CObject* element // Element to insert
)
Parameters
element
[in] Value of the element to be inserted into a sorted array
Return Value
Note
Element is not added to the array if the value for transmit invalid pointer (such as NULL).
Example:
Search
Searches for an element equal to the sample in the sorted array.
int Search(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast(
CObject* element // Sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element, if successful, -1 - if the item was not found.
Example:
Save
Saves data array in the file.
Parameters
file_handle
[in] Handle to previously opened by FileOpen (...) function binary file.
Return Value
Example:
Load
Loads data array from a file.s
Parameters
file_handle
[in] Handle to open earlier, with the function FileOpen (...), binary file.
Return Value
Note
When reading from the file array to create each element of the method is called CArrayObj::
CreateElement(int).
Example:
Type
Gets the type identifier of the array.
Return Value
Example:
CList
CList Class is a class of dynamic list of instances of the class CObject and his heirs.
Description
Class CList provides the ability to work with a list of instances of CObject and his heirs. In the class
implemented the ability to add / insert / delete items in the list, sort the list, search in sorted list. In
addition, the implemented methods of work with the file.
There are some subtleties of working with the class CList. The class has a mechanism to control
dynamic memory, so be careful when working with elements of the list.
Declaration
class CList : public CObject
Title
#include <Arrays\List.mqh>
Class Methods
Attributes
Create methods
Add methods
Delete methods
in the list
Navigation
Ordering methods
Compare methods
Search methods
Input/output
FreeMode
Gets the flag memory management when deleting list items.
Return Value
Example:
FreeMode
Sets the flag memory management when deleting list items.
void FreeMode(
bool mode // New value
)
Parameters
mode
[in] New value of the flag memory management.
Note
Setting the flag memory management - an important point in the use of class CList.Since the
elements of the list are pointers to dynamic objects, it is important to determine what to do with
them when you delete from the list.If the flag is set, then when you delete an item from the list, the
item is automatically deleted by the operator delete.If the flag is not set, it is assumed that a
pointer to the deleted object is still somewhere in the user program and will be relieved of it (the
program) then.
If the user resets the flag memory management, the user must understand their responsibility for
the removal of items in the list before completing the program, because otherwise, is not freed
memory occupied by the elements when they create new operator.When large amounts of data, it
could lead, eventually, even to break your terminal.
If the user does not reset the flag memory management, there is another "reef".Using pointers-list
items that are stored somewhere in the local variables, after removing the list, will lead to a critical
error and crashes the program user.By default, the memory management flag is set, ie the class
list, is responsible for freeing the memory elements.
Example:
Total
Gets the number of elements in the list.
Return Value
Example:
IsSorted
Gets the flag sorted list.
bool IsSorted(
int mode=0 // Sorting mode
) const
Parameters
mode=0
[in] Tested version sorting
Return Value
Flag of the sorted list. If the list is sorted by the specified option? true, otherwise? false.
Note
Flag of the sorted list can not be changed directly. Flag set by Sort (int) and resets any methods to
add / insert.
Example:
SortMode
Gets the version of the sort.
Return Value
Example:
CreateElement
Creates a new item to the list.
CObject* CreateElement()
Return Value
Pointer to the newly created element, if successful, NULL - if you can not create element.
Note
Method CreateElement () in class CList always returns NULL and does not perform any actions. If
necessary, in a derived class, method CreateElement () should be implemented.
Example:
Add
Adds an element to the end of the list.
int Add(
CObject* element // Element to add
)
Parameters
element
[in] Value of the element to add to the list.
Return Value
Note
Element is not added to the list, if the parameter does not pass valid pointer (ie NULL).
Example:
Insert
Inserts element in the list in the specified position.
int Insert(
CObject* element, // Element to insert
int pos // Position
)
Parameters
element
[in] value of the element to insert in the list
pos
[in] Position in the list to insert
Return Value
Note
Element is not added to the list, if the parameter does not pass valid pointer (ie NULL).
Example:
delete list;
}
DetachCurrent
Extracts an element from the current position without its "physical" deleteion.
CObject* DetachCurrent()
Return Value
Pointer to the removal of elements in case of success, NULL - if you can not remove the element.
Note
When removed from the list, the item is not removed in any state of the flag memory management.
Pointer to withdraw from the list of ingredients of the release element after use.
Example:
DeleteCurrent
Removes the element from the current position in the list.
bool DeleteCurrent()
Return Value
Note
Example:
Delete
Removes the element from the given position in the list.
bool Delete(
int pos // Position
)
Parameters
pos
[in] position removes the element in the list.
Return Value
Note
Example:
Clear
Removes all elements of the list.
void Clear()
Note
Example:
IndexOf
Gets the index of the list item.
int IndexOf(
CObject* element // Pointer to the element
)
Parameters
element
[in] Pointer to the list item.
Return Value
Example:
GetNodeAtIndex
Gets an item with the specified index of the list.
CObject* GetNodeAtIndex(
int pos // position
)
Parameters
pos
[in] item index in the list.
Returned value
Pointer to the item in case of success, NULL - if you can not get a pointer.
Example:
GetFirstNode
Gets the first element of the list.
CObject* GetFirstNode()
Return Value
Pointer to the first item in case of success, NULL - if you can not get a pointer.
Example:
GetPrevNode
Gets the previous element of the list.
CObject* GetPrevNode()
Return Value
Pointer to the previous element, if successful, NULL - if you can not get a pointer.
Example:
GetCurrentNode
Gets the current list item.
CObject* GetCurrentNode()
Return Value
Pointer to the current item, if successful, NULL - if you can not get a pointer.
Example:
GetNextNode
Gets the next item in the list.
CObject* GetNextNode()
Return Value
Pointer to the next item if successful, NULL - if you can not get a pointer.
Example:
GetLastNode
Gets the last element of the list.
CObject* GetLastNode()
Return Value
Pointer to the last element in the case of success, NULL - if you can not get a pointer.
Example:
Sort
Sorts a list.
void Sort(
int mode // Sorting mode
)
Parameters
mode
[in] Sorting mode.
Return Value
No.
Note
Example:
MoveToIndex
Moves the current item list to the specified position.
bool MoveToIndex(
int pos // Position
)
Parameters
pos
[in] Position in the list to move.
Return Value
Example:
Exchange
Changes elements of the list seats.
bool Exchange(
CObject* node1, // List item
CObject* node2 // List item
)
Parameters
node1
[in] List item
node2
[in] List item
Return Value
true if successful, false - if you can not change the elements in some places.
Example:
CompareList
Compares the list with another list.
bool CompareList(
CList* list // With whom we compare
)
Parameters
list
[in] A pointer to an instance of class CList-source elements for comparison.
Return Value
Example:
Search
Searches for an element equal to the model in the sorted list.
CObject* Search(
CObject* element // Sample
)
Parameters
element
[in] Sample cell to search for in the list.
Return Value
Pointer to the found item if successful, NULL - if the item was not found.
Example:
Save
Saves data in the file list.
Parameters
file_handle
[in] handle of the previously opened using the function FileOpen (...) file.
Return Value
Example:
Load
Loads list data from a file.
Parameters
file_handle
[in] Handle of the previously open, with the function FileOpen (...), binary
Return Value
Note
When reading from the file list items to create each element of the method is called CList::
CreateElement ().
Example:
Type
Gets the type identifier list.
Return Value
Example:
CTreeNode
Class CTreeNode is a class of node of the binary tree CTree.
Description
Class CTreeNode provides the ability to work with nodes of the binary tree CTree. Options of
navigation through the tree is implemented in the class. Besides that methods of work with a file are
implemented.
Declaration
class CTreeNode : public CObject
Title
#include <Arrays\TreeNode.mqh>
Class Methods
Attributes
Comparison
Search
Input/Output
Derived classes:
CTree
A descendant of class CTreeNode must have predefined methods: CreateSample that creates a new
instance of the descendant class of CTreeNode, Compare that compares values of key fields of the
descendant class of CTreeNode, Type (if it's necessary to identify a node), SaveNode and LoadNode (if
it's necessary to work with a file).
//+------------------------------------------------------------------+
//| MyTreeNode.mq5 |
//| Copyright 2010, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
//---
#include <Arrays\TreeNode.mqh>
//+------------------------------------------------------------------+
//| Describe classderived from CTreeNode. |
//+------------------------------------------------------------------+
//| Class CMyTreeNode. |
//| Purpose: Class of element of a binary tree. |
//| Descendant of class CTreeNode. |
//+------------------------------------------------------------------+
class CMyTreeNode : public CTreeNode
{
protected:
//--- user's data
long m_long; // key field of type long
double m_double; // custom variable of type double
string m_string; // custom variable of type string
datetime m_datetime; // custom variable of type datetime
public:
CMyTreeNode();
//--- methods of accessing these user's data
long GetLong(void) { return(m_long); }
void SetLong(long value) { m_long=value; }
double GetDouble(void) { return(m_double); }
void SetDouble(double value) { m_double=value; }
string GetString(void) { return(m_string); }
void SetString(string value) { m_string=value; }
datetime GetDateTime(void) { return(m_datetime); }
void SetDateTime(datetime value) { m_datetime=value; }
//--- methods of working with files
virtual bool Save(int file_handle);
virtual bool Load(int file_handle);
protected:
virtual int Compare(const CObject *node,int mode);
//--- methods of creating class instances
virtual CTreeNode* CreateSample();
};
//+------------------------------------------------------------------+
//| CMyTreeNode class constructor. |
//| INPUT: none. |
//| OUTPUT: none. |
//| REMARK: none. |
//+------------------------------------------------------------------+
void CMyTreeNode::CMyTreeNode()
{
//--- initialization of user's data
m_long =0;
m_double =0.0;
m_string ="";
m_datetime =0;
}
//+------------------------------------------------------------------+
//| Comparison with another three node by the specified algorithm. |
//| INPUT: node - array element to compare, |
//| mode - identifier of comparison algorithm. |
//| OUTPUT: result of comparison (>0,0,<0). |
//| REMARK: none. |
//+------------------------------------------------------------------+
int CMyTreeNode::Compare(const CObject *node,int mode)
{
//--- parameter mode is ignored, because tree construction algorithm is the only one
int res=0;
//--- explicit type casting
CMyTreeNode *n=node;
res=(int)(m_long-n.m_long);
//---
return(res);
}
//+------------------------------------------------------------------+
//| Creation of a new class instance. |
//| INPUT: none. |
//| OUTPUT: pointer to a new instance of class CMyTreeNode. |
//| REMARK: none. |
//+------------------------------------------------------------------+
CTreeNode* CMyTreeNode::CreateSample()
{
CMyTreeNode *result=new CMyTreeNode;
//---
return(result);
}
//+------------------------------------------------------------------+
//| Write tree node data to a file. |
//| INPUT: file_handle -handle of a file pre-opened for writing. |
//| OUTPUT: true if OK, otherwise false. |
//| REMARK: none. |
//+------------------------------------------------------------------+
bool CMyTreeNode::Save(int file_handle)
{
uint i=0,len;
//--- checks
if(file_handle<0) return(false);
//--- writing user data
//--- writing custom variable of type long
if(FileWriteLong(file_handle,m_long)!=sizeof(long)) return(false);
//--- writing custom variable of type double
if(FileWriteDouble(file_handle,m_double)!=sizeof(double)) return(false);
//--- writing custom variable of type string
len=StringLen(m_string);
//--- write string length
if(FileWriteInteger(file_handle,len,INT_VALUE)!=INT_VALUE) return(false);
//--- write the string
if(len!=0 && FileWriteString(file_handle,m_string,len)!=len) return(false);
//--- writing custom variable of type datetime
if(FileWriteLong(file_handle,m_datetime)!=sizeof(long)) return(false);
//---
return(true);
}
//+------------------------------------------------------------------+
//| Read tree node data from a file. |
//| INPUT: file_handle -handle of a file pre-opened for reading. |
//| OUTPUT: true if OK, otherwise false. |
//| REMARK: none. |
//+------------------------------------------------------------------+
bool CMyTreeNode::Load(int file_handle)
{
uint i=0,len;
//--- checks
if(file_handle<0) return(false);
//--- reading
if(FileIsEnding(file_handle)) return(false);
//--- reading custom variable of type char
//--- reading custom variable of type long
m_long=FileReadLong(file_handle);
//--- reading custom variable of type double
m_double=FileReadDouble(file_handle);
//--- reading custom variable of type string
//--- read the string length
len=FileReadInteger(file_handle,INT_VALUE);
Owner
Gets the pointer of the owner node.
CTreeNode* Owner()
Return Value
Owner
Sets the pointer of the owner node.
void Owner(
CTreeNode* node // node
)
Parameters
node
[in] New value of the pointer of the owner node.
Return Value
None.
Left
Gets the pointer of the left node.
CTreeNode* Left()
Return Value
Left
Sets the pointer of the left node.
void Left(
CTreeNode* node // node
)
Parameters
node
[in] New value of the pointer of the left node.
Return Value
None.
Right
Gets the pointer of the right node.
CTreeNode* Right()
Return Value
Right
Sets the pointer of the right node.
void Right(
CTreeNode* node // node
)
Parameters
node
[in] New value of the pointer of the right node.
Return Value
None.
Balance
Gets the node balance.
Return Value
Node balance.
BalanceL
Gets the balance of the left sub-branch of the node.
Return Value
BalanceR
Gets the balance of the right sub-branch of the node.
Return Value
CreateSample
Creates a new node sample.
Return Value
RefreshBalance
Recalculates the node balance.
int RefreshBalance()
Return Value
Node balance.
GetNext
Gets the pointer of the next node.
CTreeNode* GetNext(
CTreeNode* node // node
)
Parameters
node
[in] Node of the search start.
Return Value
SaveNode
Writes node data to a file.
bool SaveNode(
int file_handle // handle
)
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for writing.
Return Value
LoadNode
Reads node data from a file.
bool LoadNode(
int file_handle, // handle
CTreeNode* main // node
)
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for reading.
main
[in] Node for data.
Return Value
Type
Gets the identifier of the node type.
Return Value
CTree
Class CTree is a class of the binary tree of samples of class CTreeNode and its descendants.
Description
Class CTree privides the possibility to work with a binary tree of CTreeNode class samples and its
descendants. Options of adding/inserting/deleting of three elements and search in a tree are
implemented in the class. Besides that, methods of work with a file are implemented.
Note that mechanism of dynamic memory management is not implemented in class CTree (as distinct
from classes CList and CArrayObj). All tree nodes are deleted with memory release.
Declaration
class CTree : public CTreeNode
Title
#include <Arrays\Tree.mqh>
Class Methods
Attributes
Filling
Deletion
Search
Input/output
Trees of CTreeNode class descendants – descendants of class CTree get practical application.
Descendant of class CTree must have a predefined method CreateElement that creates a new sample
of descendant class CTreeNode.
//+------------------------------------------------------------------+
//| MyTree.mq5 |
//| Copyright 2010, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
//---
#include <Arrays\Tree.mqh>
#include "MyTreeNode.mqh"
//---
input int extCountedNodes = 100;
//+------------------------------------------------------------------+
//| Describe class CMyTree derived from CTree. |
//+------------------------------------------------------------------+
//| Class CMyTree. |
//| Purpose: Construction and navigation of a binary search tree. |
//+------------------------------------------------------------------+
class CMyTree : public CTree
{
public:
//--- methods of search on the tree by custom data
CMyTreeNode* FindByLong(long find_long);
//--- method of creation of the tree element
virtual CTreeNode *CreateElement();
};
//---
CMyTree MyTree;
//+------------------------------------------------------------------+
//| Creation of a new tree node. |
//| INPUT: none. |
//| OUTPUT: pointer to the new tree node of OK, or NULL. |
//| REMARK: none. |
//+------------------------------------------------------------------+
CTreeNode *CMyTree::CreateElement()
{
CMyTreeNode *node=new CMyTreeNode;
//---
return(node);
}
//+------------------------------------------------------------------+
//| Search of element in a list by value m_long. |
//| INPUT: find_long - searched value. |
//| OUTPUT: pointer of a found list element, or NULL. |
CMyTree TmpMyTree;
//--- Detach 50% of tree elements (all even)
//--- and add them to the temporary tree TmpMyTree.
beg_time=GetTickCount();
for(i=0;i<extCountedNodes;i+=2)
{
node=MyTree.FindByLong(i);
if(node!=NULL)
if(MyTree.Detach(node)) TmpMyTree.Insert(node);
}
end_time=GetTickCount();
printf("Deletion time of %d elements from MyTree is %d ms.",extCountedNodes/2,end_time-beg_time)
//--- Return the detached
node=TmpMyTree.Root();
while(node!=NULL)
{
if(TmpMyTree.Detach(node)) MyTree.Insert(node);
node=TmpMyTree.Root();
}
//--- Check work of method Save(int file_handle);
int file_handle;
file_handle=FileOpen("MyTree.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!MyTree.Save(file_handle))
{
//--- error writing to a file
//--- emergency exit
printf("%s: Error %d in %d!",__FILE__,GetLastError(),__LINE__);
//--- close file before leaving!!!
FileClose(file_handle);
return(__LINE__);
}
FileClose(file_handle);
}
//--- Check work of method Load(int file_handle);
file_handle=FileOpen("MyTree.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!TmpMyTree.Load(file_handle))
{
//--- error reading from file
//--- emergency exit
printf("%s: Error %d in %d!",__FILE__,GetLastError(),__LINE__);
//--- close file before leaving!!!
FileClose(file_handle);
return(__LINE__);
}
FileClose(file_handle);
}
//---
MyTree.Clear();
TmpMyTree.Clear();
//---
printf("End test %s. OK!",__FILE__);
//---
return(0);
}
//+------------------------------------------------------------------+
//| Function of output of node contents to journal |
//+------------------------------------------------------------------+
void NodeToLog(CMyTreeNode *node)
{
printf(" %I64d,%f,'%s','%s'",
node.GetLong(),node.GetDouble(),
node.GetString(),TimeToString(node.GetDateTime()));
}
//+------------------------------------------------------------------+
//| Function of "filling" of node with random values |
//+------------------------------------------------------------------+
void NodeSetData(CMyTreeNode *node,int mode)
{
if(mode%2==0)
{
node.SetLong(mode*MathRand());
node.SetDouble(MathPow(2.02,mode)*MathRand());
}
else
{
node.SetLong(mode*(long)(-1)*MathRand());
node.SetDouble(-MathPow(2.02,mode)*MathRand());
}
node.SetString(str_array[mode%10]);
node.SetDateTime(10000*mode);
}
Root
Gets the root node of the tree.
Return Value
CreateElement
Creates a new instance of the node.
Return Value
Insert
Adds a node to a tree.
CTreeNode* Insert(
CTreeNode* new_node // node
)
Parameters
new_node
[in] pointer of a node to insert to a tree.
Return Value
Detach
Detaches a specified node from a tree.
bool Detach(
CTreeNode* node // node
)
Parameters
node
[in] Node pointer to detach.
Return Value
Note
After detachment the node pointer is not released. The tree is balanced.
Delete
Deletes a specified node from a tree.
bool Delete(
CTreeNode* node // node
)
Parameters
node
[in] Node pointer to delete.
Return Value
Note
Clear
Deletes all nodes of a tree.
void Clear()
Return Value
None.
Note
Find
Searches for a node in a tree by sample.
CTreeNode* Find(
CTreeNode* node // node
)
Parameters
node
[in] Node that contains data-search sample.
Return Value
Save
Writes tree data to a file.
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for writing.
Return Value
Load
Reads tree data to a file.
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for reading.
Return Value
Type
Gets identifier of the tree type.
Return Value
Graphic Objects
This section contains the technical details of working with classes of graphical objects and a
description of the relevant components of the MQL5 Standard Library .
The use of classes of graphical objects, will save time when creating custom programs (scripts,
expert).
MQL5 Standard Library (in terms of graphical objects) is placed in the working directory of the
terminal in the Include\ChartObjects folder.
Class/Group Description
Base class for graphical object CChartObject Base class of a graphic object
CChartObject
CChartObject is a base class of graphic objects of chart type of the Standard MQL5 library.
Description
Class CChartObject provides the simplified access for all of its descendants to MQL5 API functions.
Declaration
class CChartObject : public CObject
Title
#include <ChartObjects\ChartObject.mqh>
Class Methods
Attributes
Assign
Delete
Shift
Object properties
Input/Output
Derived classes:
CChartObjectArrow
CChartObjectBitmap
CChartObjectBmpLabel
CChartObjectCycles
CChartObjectElliottWave3
CChartObjectEllipse
CChartObjectFiboArc
CChartObjectFiboFan
CChartObjectFiboTimes
CChartObjectHLine
CChartObjectRectangle
CChartObjectSubChart
CChartObjectText
CChartObjectTrend
CChartObjectTriangle
CChartObjectVLine
ChartId
Gets the ID chart, who owns a graphic object.
Return Value
Id chart on which the graphic object. If object not found, it returns -1.
Example:
Window
Gets the number of windows in which the chart is a graphic object.
Return Value
Number of windows in which the chart is a graphic object (0 - main window). If object not found, it
returns -1.
Example:
Return Value
Name of the graphic object tied to an instance of the class. If object not found, returns NULL.
bool Name(
string name // new name
)
Parameters
name
[in] The new name of the graphic object.
Return Value
Example:
NumPoints
Gets the number of anchor points of a graphic object.
Return Value
Number of points linking a graphic object that is bound to an instance of the class. If not bound
object, it returns 0.
Example:
Attach
Binds a graphical object to an instance of the class.
bool Attach(
long chart_id, // Chart ID
string name, // Name of the object
int window, // Chart window
int points // Number of points
)
Parameters
chart_id
[out] Chart identifier.
name
[in] Name of the graphic object.
window
[in] Chart window number (0 – main window).
points
[in] Number of points anchor graphic object.
Return Value
Example:
SetPoint
Sets the new coordinates of this anchor point graphic object.
bool SetPoint(
int point, // Point number
datetime new_time, // Time coordinate
double new_price // Price coordinate
)
Parameters
point
[in] Number anchor point graphic object.
new_time
[in] The new value of the coordinates of this point of time bindings.
new_price
[in] New value coordinates of the price specified anchor point.
Return Value
true - if successful, false - if you can not change the coordinates of the point.
Example:
Delete
Removes a graphical object with the attached chart.
bool Delete()
Return Value
Example:
Detach
Untie graphic object.
bool Detach()
Return Value
Example:
ShiftObject
Moves a graphic object.
bool ShiftObject(
datetime d_time, // Increment of time coordinate
double d_price // Increment of price coordinate
)
Parameters
d_time
[in] Increment the coordinates of all points of time bindings
d_price
[in] Increment the coordinates of the prices of all waypoints.
Return Value
Example:
ShiftPoint
Moves a specified point anchor graphic.
bool ShiftPoint(
int point, // Point number
datetime d_time, // Increment of time coordinate
double d_price // Increment of price coordinate
)
Parameters
point
[in] Number anchor point graphic object.
d_time
[in] Increment the coordinates of time specified anchor point.
d_price
[in] Increment the coordinates of the price specified anchor point.
Return Value
Example:
datetime Time(
int point // Point number
) const
Parameters
point
[in] Number anchor point graphic object.
Return Value
Coordinates of time specified anchor point graphic object that is bound to an instance of the class.
If not bound object or the object is not this point, it returns 0.
bool Time(
int point, // Point number
datetime new_time // Time
)
Parameters
point
[in] Number anchor point graphic object.
new_time
[in] The new value of the coordinates of this point of time anchor graphic object.
Return Value
true - if successful, false - if you can not change the coordinate of time.
Example:
{
//--- set time of point chart object
object.Time(i,TimeCurrent());
}
}
}
double Price(
int point // Point number
) const
Parameters
point
[in] Number anchor point graphic object.
Return Value
Coordinate prices specified anchor point graphic object that is bound to an instance of the class. If
not bound object or the object is not this point, it returns EMPTY_VALUE.
bool Price(
int point, // Point number
double new_price // Price
)
Parameters
point
[in] Number anchor point graphic object.
new_price
[in] News value coordinates of the price specified anchor point graphic object.
Return Value
true - if successful, false - if you can not change the coordinate prices.
Example:
if(point_price!=price)
{
//--- set price of point chart object
object.Price(i,price);
}
}
}
Return Value
Color line of graphic object, assigned to the class instance. If there is no object assigned, it returns
CLR_NONE.
bool Color(
color new_color // New color
)
Parameters
new_color
[in] New value line color graphic object.
Return Value
Example:
Return Value
Style line of the graphic object, assigned to the class instance. If there is no object assigned, it
returns WRONG_VALUE.
bool Style(
ENUM_LINE_STYLE new_style // Style
)
Parameters
new_style
[in] New value-style line drawing object.
Return Value
Example:
Return Value
The thickness of the line graphic object that is bound to an instance of the class. If not bound
object, it returns -1.
bool Width(
int new_width // Thickness
)
Parameters
new_width
[in] The new value of the thickness of the line graphic object.
Return Value
Example:
Return Value
Flag of drawing in the background, a graphic object that is bound to an instance of the class. If not
bound object returns false.
bool Background(
bool background // Value of the flag
)
Parameters
background
[in] New value of the flag drawing a graphic object in the background.
Return Value
Example:
Return Value
Flag "slate", a graphic object that is bound to an instance of the class. If not bound object returns
false.
bool Selected(
bool selected // Value of the flag
)
Parameters
selected
[in] New value of the flag "reprimand" graphic object.
Return Value
Example:
Return Value
Flag "selectable", a graphic object that is bound to an instance of the class. If not bound object
returns false.
bool Selectable(
bool selectable // Value of the flag
)
Parameters
selectable
[in] New value of the flag "selectable" graphic object.
Return Value
Example:
Return Value
Description (text) graphic object that is bound to an instance of the class. If no bound object, it
returns NULL.
bool Description(
string text // Text
)
Parameters
text
[in] New value descriptions (text) graphic object.
Return Value
true - if successful, false - if you can not change the description (text).
Example:
Return Value
Flags visibility graphic object that is bound to an instance of the class. If not bound object, it
returns 0.
bool Timeframes(
int new_timeframes // Visibility flags
)
Parameters
new_timeframes
[in] New flags visibility graphic object.
Return Value
true - if successful, false - if you can not change the flags of visibility.
Example:
CreateTime
Gets the time to create graphical object.
Return Value
Time to create graphical object that is bound to an instance of the class. If not bound object, it
returns 0.
Example:
Return Value
Number of levels of graphical object that is bound to an instance of the class. If not bound object, it
returns 0.
bool LevelsCount(
int levels // Number of levels
)
Parameters
levels
[in] the number of new levels of graphic object.
Return Value
true - if successful, false - if you can not change the number of levels.
Example:
color LevelColor(
int level // Level number
) const
Parameters
level
[in] Number of levels of graphical object.
Return Value
Color Line level specified graphic object that is bound to an instance of the class. If not bound
object or the object is no specified level, it returns CLR_NONE.
bool LevelColor(
int level, // Level number
color new_color // New color
)
Parameters
level
[in] Number of levels of graphical object.
new_color
[in] New value line color of the level of graphic object.
Return Value
Example:
{
//--- set level color of chart object
object.LevelColor(i,clrRed);
}
}
}
ENUM_LINE_STYLE LevelStyle(
int level // Level number
) const
Parameters
level
[in] Number of levels of graphical object.
Return Value
Line style specified level graphical object that is bound to an instance of the class. If not bound
object or the object is no specified level of returns WRONG_VALUE.
int LevelStyle(
int level, // Level number
ENUM_LINE_STYLE style // Line Style
)
Parameters
level
[in] Number of levels of graphical object.
style
[in] New value-style line level specified graphical object.
Return Value
Example:
{
//--- set level style of chart object
object.LevelStyle(i,STYLE_SOLID);
}
}
}
int LevelWidth(
int level // Level number
) const
Parameters
level
[in] Number of levels of graphical object.
Return Value
The thickness of the lines of the level of graphical object that is bound to an instance of the class.
If not bound object or the object is no specified level, it returns -1.
bool LevelWidth(
int level, // Level number
int new_width // New width
)
Parameters
level
[in] Number of levels of graphical object.
new_width
[in] New value line thickness specified level graphical object.
Return Value
position of the found element, if successful, -1 - if the item was not found.
Example:
{
//--- set level width of chart object
object.LevelWidth(i,1);
}
}
}
double LevelValue(
int level // Level number
) const
Parameters
level
[in] Number of levels of graphical object.
Return Value
The value of this level of graphical object that is bound to an instance of the class. If not bound
object or the object is no level specified, returns EMPTY_VALUE.
bool LevelValue(
int level, // Level number
double new_value // New value
)
Parameters
level
[in] Number of levels of graphical object.
new_value
[in] New value of the level of graphic object.
Return Value
Example:
{
//--- set level value of chart object
object.LevelValue(i,0.1*i);
}
}
}
string LevelDescription(
int level // Level number
) const
Parameters
level
[in] Number of levels of graphical object.
Return Value
Description (text) of the level of graphical object that is bound to an instance of the class. If not
bound object or the object is no specified level, returns NULL.
bool LevelDescription(
int level , // Level number
string text // Text
)
Parameters
level
[in] Number of level of graphical object.
text
[in] New value of description (text) of the level of graphic object.
Return Value
true – if successful, false - if you can not change the description (text).
Example:
{
//--- set level description of chart object
object.LevelDescription(i,"Level_"+IntegerToString(i));
}
}
}
GetInteger
Provides simplified access to the functions of API MQL5 ObjectGetInteger() for integer-value
properties (of type bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to an
instance of the class graphic.There are two versions of a function call:
long GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier=-1 // Modifier
) const
Parameters
prop_id
[in] ID of double-graphic properties.
modifier=-1
[in] Modifier (index) double-features.
Return Value
bool GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier, // Modifier
long& value // Link to variable
) const
Parameters
prop_id
[in] ID integer-graphic properties of the object.
modifier
[in] Modifier (index) integer-property.
value
[out] Reference to a variable to accommodate the integer-value properties.
Return Value
Example:
{
CChartObject object;
//--- get color of chart object by easy method
printf("Objects color is %s",ColorToString(object.GetInteger(OBJPROP_COLOR),true));
//--- get color of chart object by classic method
long color_value;
if(!object.GetInteger(OBJPROP_COLOR,0,color_value))
{
printf("Get integer property error %d",GetLastError());
return;
}
else
printf("Objects color is %s",color_value);
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels width by easy method
printf("Level %d width is %d",i,object.GetInteger(OBJPROP_LEVELWIDTH,i));
//--- get levels width by classic method
long width_value;
if(!object.GetInteger(OBJPROP_LEVELWIDTH,i,width_value))
{
printf("Get integer property error %d",GetLastError());
return;
}
else
printf("Level %d width is %d",i,width_value);
}
}
SetInteger
Provides simplified access to the functions of API MQL5 ObjectSetInteger() to change the integer-
properties (with types bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to
an instance of the class graphic.There are two versions of a function call:
bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
long value // Value
)
Parameters
prop_id
[in] ID integer-graphic properties of the object.
value
[in] new mutable integer-value properties.
bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier, // Modifier
long value // Value
)
Parameters
prop_id
[in] ID integer-graphic properties of the object.
modifier
[in] Modifier (index) integer-property.
value
[in] new mutable integer-value properties.
Return Value
Example:
if(!object.SetInteger(OBJPROP_COLOR,clrRed))
{
printf("Set integer property error %d",GetLastError());
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- set levels width
if(!object.SetInteger(OBJPROP_LEVELWIDTH,i,i))
{
printf("Set integer property error %d",GetLastError());
return;
}
}
}
GetDouble
Provides simplified access to the functions of API MQL5 ObjectGetDouble() to get the values double-
properties (having type float and double) of the graphic object, assigned to the class instance. There
are two versions of a function call:
double GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier=-1 // Modifier
) const
Parameters
prop_id
[in] ID of double-graphic properties.
modifier=-1
[in] Modifier (index) double-features.
Return Value
If successful, it returns the value of property of double type, if error, it returns EMPTY_VALUE.
bool GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier, // Modifier
double& value // Link to variable
) const
Parameters
prop_id
[in] ID of double-graphic properties.
modifier
[in] Modifier (index) double-features.
value
[out] Reference to a variable to accommodate the double-value properties.
Return Value
Example:
{
CChartObject object;
//---
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels value by easy method
printf("Level %d value=%f",i,object.GetDouble(OBJPROP_LEVELVALUE,i));
//--- get levels value by classic method
double value;
if(!object.SetDouble(OBJPROP_LEVELVALUE,i,value))
{
printf("Get double property error %d",GetLastError());
return;
}
else
printf("Level %d value=%f",i,value);
}
}
SetDouble
Provides simplified access to the functions of API MQL5 ObjectSetDouble() to change the double-
properties (having type float and double) bound to an instance of the class graphic object. There are
two versions of a function call:
bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
double value // Value
)
Parameters
prop_id
[in] ID of double-graphic properties.
value
[in] New value mutable double-features.
bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier, // Modifier
double value // Value
)
Parameters
prop_id
[in] ID of double-graphic properties.
modifier
[in] Modifier (index) of double-property.
value
[in] New value mutable double-property.
Return Value
Example:
for(int i=0;i<object.LevelsCount();i++)
{
//--- set level value of chart object
if(!object.SetDouble(OBJPROP_LEVELVALUE,i,0.1*i))
{
printf("Set double property error %d",GetLastError());
return;
}
}
}
GetString
Provides simplified access to the functions of API MQL5 ObjectGetString() for string-value properties,
is bound to an instance of the class graphic object. There are two versions of a function call:
string GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier=-1 // Modifier
) const
Parameters
prop_id
[in] Identifier string-properties of graphic object.
modifier=-1
[in] Modifier (index) string-properties.
Return Value
Value of string-property.
bool GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier, // Modifier
string& value // Link to variable
) const
Parameters
prop_id
[in] Identifier string-properties of graphic object.
modifier
[in] Modifier (index) string-properties.
value
[out] Reference to a variable to accommodate the string-value properties.
Return Value
Example:
CChartObject object;
string value;
//--- get name of chart object by easy method
printf("Object name is '%s'",object.GetString(OBJPROP_NAME));
//--- get name of chart object by classic method
if(!object.GetString(OBJPROP_NAME,0,value))
{
printf("Get string property error %d",GetLastError());
return;
}
else
printf("Object name is '%s'",value);
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels description by easy method
printf("Level %d description is '%s'",i,object.GetString(OBJPROP_LEVELTEXT,i));
//--- get levels description by classic method
if(!object.GetString(OBJPROP_LEVELTEXT,i,value))
{
printf("Get string property error %d",GetLastError());
return;
}
else
printf("Level %d description is '%s'",i,value);
}
}
SetString
Provides simplified access to the functions of API MQL5 ObjectSetString() to change the properties of
string-tied to the instance of the class graphic object. There are two versions of a function call:
bool SetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
string value // Value
)
Parameters
prop_id
[in] Identifier string-properties of graphic object.
value
[in] New value mutable string-properties.
bool SetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier, // Modifier
string value // Value
)
Parameters
prop_id
[in] Identifier string-properties of graphic object.
modifier
[in] Modifier (index) string-properties.
value
[in] New value mutable string-properties.
Return Value
Example:
{
printf("Set string property error %d",GetLastError());
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- set levels description
if(!object.SetString(OBJPROP_LEVELTEXT,i,"Level_"+IntegerToString(i)))
{
printf("Set string property error %d",GetLastError());
return;
}
}
}
Save
Saves parameters of the object in the file.
Parameters
file_handle
[in] handle of the previously opened using the function FileOpen (...) file.
Return Value
Example:
Load
Loads the parameters of the object from the file.
Parameters
file_handle
[in] handle of the previously opened using the function FileOpen (...) file.
Return Value
Example:
Type
Gets the type identifier graphic object.
Return Value
Example:
Objects Lines
A group of graphic objects "Lines".
This section contains the technical details of working with a group of classes of graphical objects
"Lines" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectVLine
Class CChartObjectVLine is a class for simplified access to "Vertical Line" graphic object properties.
Description
Declaration
class CChartObjectVLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Vertical Line".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time // Time coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time
[in] Time coordinate of the anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectHLine
Class CChartObjectHLine is a class for simplified access to "Horizontal Line" graphic object
properties.
Description
Declaration
class CChartObjectHLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Horizontal Line".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
double price // Price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
price
[in] Price coordinate of the anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectTrend
Class CChartObjectTrend is a class for simplified access to "Trend Line" graphic object properties.
Description
Declaration
class CChartObjectTrend : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectChannel
CChartObjectFibo
CChartObjectFiboChannel
CChartObjectFiboExpansion
CChartObjectGannFan
CChartObjectGannGrid
CChartObjectPitchfork
CChartObjectRegression
CChartObjectStdDevChannel
CChartObjectTrendByAngle
See also
Object types, Graphic objects
Create
Creates graphic object "Trend Line".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // 1st time coordinate
double price1, // 1st price coordinate
datetime time2, // 2nd time coordinate
double price2 // 2nd price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Returned value
The value of "Ray Left" property, assigned to the class instance. If there is no object assigned, it
returns false.
bool RayLeft(
bool ray // flag
)
Parameters
ray
[in] New value of the "Ray Left" property.
Returned value
Returned value
The value of "Ray Right" property, assigned to the class instance. If there is no object assigned, it
returns false.
bool RayRight(
bool ray // flag
)
Parameters
ray
[in] New value of the "Ray Right" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...) .
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...).
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectTrendByAngle
Class CChartObjectTrendByAngle is a class for simplified access to "Trend Line by Angle" graphic
object properties.
Description
Declaration
class CChartObjectTrendByAngle : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectGannLine
See also
Object types, Graphic objects
Create
Creates graphic object "Trend Line by Angle"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // 1st time coordinate
double price1, // 1st price coordinate
datetime time2, // 2nd time coordinate
double price2 // 2nd price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Returned value
The value of "Angle" property, assigned to the class instance. If there is no object assigned, it
returns EMPTY_VALUE.
bool Angle(
double angle // Angle
)
Parameters
angle
[in] New value of the "Angle" property.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectCycles
Class CChartObjectCycles is a class for simplified access to "Cyclic Lines" graphic object properties.
Description
Declaration
class CChartObjectCycles : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Cyclic Lines"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // 1st time coordinate
double price1, // 1st price coordinate
datetime time2, // 2nd time coordinate
double price2 // 2nd price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
Objects Channels
A group of graphic objects "Channels".
This section contains the technical details of working with a group of classes of graphical objects
"Channels" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectChannel
The CChartObjectChannel is a class for simplified access to "Equidistant Channel" graphic object
properties.
Description
Declaration
class CChartObjectChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Equidistant Channel"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // Time coordinate
double price1,
datetime time2,
double price2,
datetime time3,
double price3
)
Parameters
chart_id
[in] Chart ID (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectRegression
Class CChartObjectRegression is a class for simplified access to "Linear Regression Channel" graphic
object properties.
Description
Declaration
class CChartObjectRegression : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Linear Regression Channel"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // First time coordinate
datetime time2 // Second time coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectStdDevChannel
Class CChartObjectStdDevChannel is a class for simplified access to "Standard Deviation Channel"
graphic object properties.
Description
Declaration
class CChartObjectStdDevChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Standard Deviation Channel"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
datetime time2, // Second time coordinate
double deviation // Deviation
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
deviation
[in] Numerical value for "Deviation" property.
Returned value
Returned value
Numerical value of "Deviation" property, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool Deviation(
double deviation // Deviation
)
Parameters
deviation
[in] New value for "Deviation" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...) .
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...) .
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectPitchfork
Class CChartObjectPitchfork is a class for simplified access to "Andrew's Pitchfork" graphic object
properties.
Description
Declaration
class CChartObjectPitchfork : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Andrew's Pitchfork"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // 1st time coordinate
double price1, // 1st price coordinate
datetime time2, // ...
double price2,
datetime time3,
double price3
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point..
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the first anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
Gann Tools
A group of graphic objects "Gann Tools".
This section contains the technical details of working with a group of classes of graphical objects
"Gann Tools" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectGannLine
Class CChartObjectGannLine is a class for simplified access to "Gann Line" graphic object properties.
Description
Declaration
class CChartObjectGannLine : public CChartObjectTrendByAngle
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Gann Line".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double ppb // Pips per bar
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
ppb
[in] Pips per bar.
Returned value
Returned value
Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool PipsPerBar(
double ppb // Pips per bar
)
Parameters
ppb
[in] New value for "Pips per bar" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectGannFan
Class CChartObjectGannFan is a class for simplified access to "Gann Fan" graphic object properties.
Description
Declaration
class CChartObjectGannFan : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Gann Fan".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double ppb // Pips per bar
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
ppb
[in] Pips per bar.
Returned value
Returned value
Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool PipsPerBar(
double ppb // Pips per bar
)
Parameters
ppb
[in] New value for "Pips per bar" property.
Returned value
Returned value
Value of the "Downtrend" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Downtrend(
bool downtrend // Flag value
)
Parameters
downtrend
[in] New value for "Downtrend" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectGannGrid
Class CChartObjectGannGrid is a class for simplified access to "Gann Grid" graphic object properties.
Description
Declaration
class CChartObjectGannGrid : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Gann Grid".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double ppb // Pips per bar
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
ppb
[in] Pips per bar.
Returned value
Returned value
Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool PipsPerBar(
double ppb // Pips per bar
)
Parameters
ppb
[in] New value for "Pips per bar" property.
Returned value
Returned value
Value of "Downtrend" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Downtrend(
bool downtrend // Flag value
)
Parameters
downtrend
[in] New value for "Downtrend" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Type
Returns graphic object type identifier.
Returned value
Fibonacci Tools
A group of graphic objects "Fibonacci Tools".
This section contains the technical details of working with a group of classes of graphical objects
"Fibonacci Tools" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectFibo
Class CChartObjectFibo is a class for simplified access to "Fibonacci Retracement" graphic object
properties.
Description
Declaration
class CChartObjectFibo : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Retracement".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2 // Second price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectFiboTimes
Class CChartObjectFiboTimes is a class for simplified access to "Fibonacci Time Zones" graphic object
properties.
Description
Declaration
class CChartObjectFiboTimes : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Time Zones".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2 // Second price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectFiboFan
Class CChartObjectFiboFan is a class for simplified access to "Fibonacci Fan" graphic object
properties.
Description
Declaration
class CChartObjectFiboFan : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Fan".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2 // Second price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectFiboArc
Class CChartObjectFiboArc is a class for simplified access to "Fibonacci Arc" graphic object properties.
Description
Declaration
class CChartObjectFiboArc : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Arc"
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
double scale // Scale
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
scale
[in] Scale.
Returned value
Returned value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool Scale(
double scale // Scale
)
Parameters
scale
[in] New value for "Scale" property.
Returned value
Returned value
Value of "Ellipse" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Ellipse(
bool ellipse // flag value
)
Parameters
ellipse
[in] New value for "Scale" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectFiboChannel
Class CChartObjectFiboChannel is a class for simplified access to "Fibonacci Channel" graphic object
properties.
Description
Declaration
class CChartObjectFiboChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Channel".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3 // Third price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectFiboExpansion
Class CChartObjectFiboExpansion is a class for simplified access to "Fibonacci Expansion" graphic
object properties.
Description
Declaration
class CChartObjectFiboExpansion : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Fibonacci Expansion".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3 // Third price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
Elliott Tools
A group of graphic objects "Elliott Tools".
This section contains the technical details of working with a group of classes of graphical objects
"Elliott Tools" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectElliottWave3
Class CChartObjectElliottWave3 is a class for simplified access to "Correcting Wave" graphic object
properties.
Description
Declaration
class CChartObjectElliottWave3 : public CChartObject
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectElliottWave5
See also
Object types, Graphic objects
Create
Creates graphic object "Correcting Wave".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3 // Third price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Time coordinate of the third anchor point.
Returned value
Returned value
Value of "Degree" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Degree(
ENUM_ELLIOT_WAVE_DEGREE degree // property value
)
Parameters
degree
[in] New value for "Degree" property.
Returned value
Returned value
Value of "Lines" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Lines(
bool lines // flag value
)
Parameters
lines
[in] New value for "Lines" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectElliottWave5
Class CChartObjectElliottWave5 is a class for simplified access to "Impulse Wave" graphic object
properties.
Description
Declaration
class CChartObjectElliottWave5 : public CChartObjectElliottWave3
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Impulse Wave".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3, // Third price coordinate
datetime time4, // Fourth time coordinate
double price4, // Fourth price coordinate
datetime time5 // Fifth time coordinate
double price5, // Fifth price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
time4
[in] Time coordinate of the fourth anchor point.
price4
[in] Price coordinate of the fourth anchor point.
time5
[in] Time coordinate of the fifth anchor point.
price5
[in] Price coordinate of the fifth anchor point.
Returned value
Type
Returns graphic object type identifier.
Returned value
Objects Shapes
A group of graphic objects "Shapes".
This section contains the technical details of working with a group of classes of graphical objects
"Shapes" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectRectangle
Class CChartObjectRectangle is a class for simplified access to "Rectangle" graphic object properties.
Description
Declaration
class CChartObjectRectangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Rectangle".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2 // Second price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectTriangle
Class CChartObjectTriangle is a class for simplified access to "Triangle" graphic object properties.
Description
Declaration
class CChartObjectTriangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Triangle".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
long window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3 // Third price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
CChartObjectEllipse
Class CChartObjectEllipse is a class for simplified access to "Ellipse" graphic object properties.
Description
Declaration
class CChartObjectEllipse : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Input/output
See also
Object types, Graphic objects
Create
Creates graphic object "Ellipse".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time1, // First time coordinate
double price1, // First price coordinate
datetime time2, // Second time coordinate
double price2, // Second price coordinate
datetime time3, // Third time coordinate
double price3 // Third price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time1
[in] Time coordinate of the first anchor point.
price1
[in] Price coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
price2
[in] Price coordinate of the second anchor point.
time3
[in] Time coordinate of the third anchor point.
price3
[in] Price coordinate of the third anchor point.
Returned value
Type
Returns object type identifier of the graphic object.
Returned value
Objects Arrows
Group for graphic objects Arrows.
This section contains the technical details of working with a group of classes of graphical objects
"Arrow" and a description of the relevant components of the MQL5 Standard Library . In essence, the
arrow - this is some icon to be displayed to the user, which matches a certain code. There are two
types of graphical objects "Arrow" to display icons on the charts:
Object "Arrow", which allows you to specify the code icon displayed object.
Group objects to display certain types of icons (and the corresponding certain fixed code).
CChartObjectArrow Arrow
CChartObjectArrowCheck Check
CChartObjectArrowDown Arrow Up
CChartObjectArrowThumbDown Thumbs Up
See also
Object types, Methods of binding sites, Graphic objects
CChartObjectArrow
Class CChartObjectArrow is a class for simplified access to "Arrow" graphic object properties.
Description
Class CChartObjectArrow provides access to common properties of objects "Arrow" to all of its
descendants.
Declaration
class CChartObjectArrow : public CChartObject
Title
#include <ChartObjects\ChartObjectsArrow.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Methods of binding sites, Graphic objects
Create
Creates graphic object "Arrow".
bool Create(
long chart_id, // Chart ID
string name, // Object Name
int window, // Chart Window
datetime time, // Time
double price, // Price
char code // Arrow Code
)
Parameters
chart_id
[in] Chart Identifier (0 – current chart).
name
[in] Object name (Should be unique).
window
[in] Chart window number (0 – base window).
time
[in] Time coordinate.
price
[in] Price coordinate.
code
[in] "Arrow" code (Wingdings).
Returned value
Example:
return;
}
//--- use arrow
//--- . . .
}
Returned value
Symbol code of "Arrow" object, assigned to the class instance. If there is no object assigned, it
returns 0.
bool ArrowCode(
char code // Code value
)
Parameters
code
[in] new value for "arrow" code (Wingdings).
Returned value
Example:
arrow.ArrowCode(code);
}
//--- use arrow
//--- . . .
}
Returned value
Anchor type of "Arrow" object, assigned to the class instance. If there is no object assigned, it
returns WRONG_VALUE.
bool Anchor(
ENUM_ARROW_ANCHOR new_color // new color
)
Parameters
new_color
[in] New value of color for line of the graphic object.
Returned value
Example:
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...) .
Returned value
Example:
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the file already opened using by function FileOpen(...).
Returned value
Example:
Type
Returns graphic object type identifier
Returned value
Example:
Description
Classes "Arrows with fixed code" provides access to the object properties.
Declarations
class CChartObjectArrowCheck : public CChartObjectArrow;
class CChartObjectArrowDown : public CChartObjectArrow;
class CChartObjectArrowUp : public CChartObjectArrow;
class CChartObjectArrowStop : public CChartObjectArrow;
class CChartObjectArrowThumbDown : public CChartObjectArrow;
class CChartObjectArrowThumbUp : public CChartObjectArrow;
class CChartObjectArrowLeftPrice : public CChartObjectArrow;
class CChartObjectArrowRightPrice : public CChartObjectArrow;
Title
<ChartObjects\ChartObjectsArrow.mqh>
Class Methods
Create
Properties
Input/output
See also
Create
Creates graphic object "Arrow with fixed code".
bool Create(
long chart_id, // Chart ID
string name, // Object Name
int window, // Chart Window
datetime time, // Time
double price // Price
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] Unique name of the object to create.
window
[in] Chart window number (0 – base window).
time
[in] Time coordinate.
price
[in] Price coordinate.
Returned value
Example:
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//---
return;
}
//--- use arrow
//--- . . .
}
ArrowCode
Prohibits code changes for "Arrow".
bool ArrowCode(
char code // code value
)
Parameters
code
[in] any value
Returned value
Always false.
Example:
Type
Returns graphic object type identifier
Returned value
Example:
Object Controls
A group of graphic objects "Object Controls".
This section contains the technical details of working with a group of classes of graphical objects
"Object Controls" and a description of the relevant components of the MQL5 Standard Library .
See also
Object types, Graphic objects
CChartObjectText
Class CChartObjectText is a class for simplified access to "Text" graphic object properties.
Description
Declaration
class CChartObjectText : public CChartObject
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectLabel
See also
Object types, Object properties, Methods of binding sites, Graphic objects
Create
Creates graphic object "Text".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time, // Time coordinate
double price // Price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time
[in] Time coordinate of the anchor point.
price
[in] Price coordinate of the anchor point.
Returned value
Returned value
Value of "Angle" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool Angle(
double angle // new angle
)
Parameters
angle
[in] New value for "Angle" property.
Returned value
Returned value
Value of "Font" property of the object, assigned to the class instance. If there is no object assigned,
it returns "".
bool Font(
string font // new font
)
Parameters
font
[in] New value for "Font" property.
Returned value
Returned value
Value of "FontSize" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool FontSize(
int size // new font size
)
Parameters
size
[in] New value for "Font" property.
Returned value
Returned value
Value of "Anchor" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Anchor(
ENUM_ANCHOR_POINT anchor // new value
)
Parameters
anchor
[in] New value for "Anchor" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectLabel
Class CChartObjectLabel is a class for simplified access to "Label" graphic object properties.
Description
Declaration
class CChartObjectLabel : public CChartObjectText
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectEdit
See also
Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects
Create
Creates graphic object "Label".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
int X, // X coordinate
int Y, // Y coordinate
int sizeX, // X size
int sizeY // Y size
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
X
[in] X coordinate.
Y
[in] Y coordinate.
sizeX
[in] X size.
sizeY
[in] Y size.
Returned value
Returned value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool X_Distance(
int X // new value
)
Parameters
X
[in] New value for "X_Distance" property.
Returned value
Returned value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Y_Distance(
int Y // new value
)
Parameters
Y
[in] New value for "Y_Distance" property.
Returned value
X_Size
Gets the value of "X_Size" property.
Returned value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
Y_Size
Gets the value of "Y_Size" property.
Returned value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
Returned value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Corner(
ENUM_BASE_CORNER corner // new value
)
Parameters
corner
[in] New value for "Corner" property.
Returned value
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time // any value
)
Parameters
time
[in] Any value of datetime type.
Returned value
always false.
Price
Prohibits changes of the price coordinate.
bool Price(
double price // any value
)
Parameters
price
[in] Any value of double type.
Returned value
always false.
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectEdit
Class CChartObjectEdit is a class for simplified access to "Edit" graphic object properties.
Description
Declaration
class CChartObjectEdit : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Properties
Input/output
Derived classes:
CChartObjectButton
See also
Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects
Create
Creates graphic object "Edit".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
int X, // X coordinate
int Y, // Y coordinate
int sizeX, // X size
int sizeY // Y size
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
X
[in] X coordinate.
Y
[in] Y coordinate.
sizeX
[in] X size.
sizeY
[in] Y size.
Returned value
X_Size
Sets new value for "X_Size" property.
bool X_Size(
int size // new size
)
Parameters
size
[in] New value for "X_Size" property.
Returned value
Y_Size
Sets new value for "Y_Size" property.
bool Y_Size(
int size // new size
)
Parameters
size
[in] New value for "Y_Size" property.
Returned value
Returned value
Value of "BackColor" property of the object, assigned to the class instance. If there is no object
assigned, it returns CLR_NONE.
bool BackColor(
color new_color // new background color
)
Parameters
new_color
[in] New value for "BackColor" property.
Returned value
Angle
Prohibits changes of the "Angle" property.
bool Angle(
double angle // any value
)
Parameters
angle
[in] Any value of double type.
Returned value
always false.
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectButton
Class CChartObjectButton is a class for simplified access to "Button" graphic object properties.
Description
Declaration
class CChartObjectButton : public CChartObjectEdit
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects
Returned value
Value of "State" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool State(
bool state // new state value
)
Parameters
X
[in] New value for "State" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectSubChart
Class CChartObjectSubChart is a class for simplified access to "Chart" graphic object properties.
Description
Declaration
class CChartObjectSubChart : public CChartObject
Title
#include <ChartObjects\ChartObjectsSubChart.mqh>
Class Methods
Create
Properties
Input/output
See also
Create
Creates graphic object "SubChart".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
int X, // X coordinate
int Y, // Y coordinate
int sizeX, // X size
int sizeY // Y size
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
X
[in] X coordinate.
Y
[in] Y coordinate.
sizeX
[in] X size.
sizeY
[in] Y size.
Returned value
Returned value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool X_Distance(
int X // new value
)
Parameters
X
[in] New value for "X_Distance" property.
Returned value
Returned value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Y_Distance(
int Y // new value
)
Parameters
Y
[in] New value for "Y_Distance" property.
Returned value
ENUM_BASE_CORNER Corner() const
Returned value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Corner(
ENUM_BASE_CORNER corner // new value
)
Parameters
corner
[in] New value for "Corner" property.
Returned value
Returned value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool X_Size(
int X // new value
)
Parameters
X
[in] New value for "X_Size" property.
Returned value
Returned value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Y_Size(
int Y // new value
)
Parameters
Y
[in] New value for "Y_Size" property.
Returned value
Returned value
Value of "Symbol" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
bool Symbol(
string symbol // new symbol
)
Parameters
symbol
[in] New value for "Symbol" property.
Returned value
Returned value
Value of "Period" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Period(
int period // new period
)
Parameters
period
[in] New value for "Period" property.
Returned value
Returned value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool Scale(
double scale // new scale
)
Parameters
scale
[in] New value for "Scale" property.
Returned value
Returned value
Value of "DateScale" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool DateScale(
bool scale // new value
)
Parameters
scale
[in] New value for "DateScale" property.
Returned value
Returned value
Value of "PriceScale" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool PriceScale(
bool scale // new value
)
Parameters
scale
[in] New value for "PriceScale" property.
Returned value
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time // any value
)
Parameters
time
[in] Any value of datetime type.
Returned value
always false.
Price
Prohibits changes of the price coordinate.
bool Price(
double price // any value
)
Parameters
price
[in] Any value of double type.
Returned value
always false.
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectBitmap
Class CChartObjectBitmap is a class for simplified access to "Bitmap" graphic object properties.
Description
Declaration
class CChartObjectBitmap : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Object properties, Graphic objects
Create
Creates graphic object "Bitmap".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
datetime time, // Time coordinate
double price // Price coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] An unique name of the object to create.
window
[in] Chart window number (0 – base window).
time
[in] Time coordinate of the anchor point.
price
[in] Price coordinate of the anchor point.
Returned value
Returned value
Value of "BmpFile" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool BmpFile(
string name // new file name
)
Parameters
X
[in] New value for "BmpFile" property.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectBmpLabel
Class CChartObjectBmpLabel is a class for simplified access to "Bitmap Label" graphic object
properties.
Description
Declaration
class CChartObjectBmpLabel : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create
Properties
Input/output
See also
Create
Creates graphic object "BmpLabel".
bool Create(
long chart_id, // Chart identifier
string name, // Object name
int window, // Chart window
int X, // X coordinate
int Y // Y coordinate
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] A unique name of the object to create.
window
[in] Chart window number (0 – base window).
X
[in] X coordinate.
Y
[in] Y coordinate.
Returned value
Returned value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool X_Distance(
int X // new value
)
Parameters
X
[in] New value for "X_Distance" property.
Returned value
Returned value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Y_Distance(
int Y // new value
)
Parameters
Y
[in] New value for "Y_Distance" property.
Returned value
ENUM_BASE_CORNER Corner() const
Returned value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Corner(
ENUM_BASE_CORNER corner // new value
)
Parameters
corner
[in] New value for "Corner" property.
Returned value
X_Size
Gets the value of "X_Size" property.
Returned value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
Y_Size
Gets the value of "Y_Size" property.
Returned value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
Returned value
Value of "BmpFileOn" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
bool BmpFileOn(
string name // file name
)
Parameters
name
[in] New value for "BmpFileOn" property.
Returned value
Returned value
Value of "BmpFileOff" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
bool BmpFileOff(
string name // file name
)
Parameters
name
[in] New value for "BmpFileOff" property.
Returned value
Returned value
Value of "State" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool State(
bool state // new state value
)
Parameters
X
[in] New value for "State" property.
Returned value
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time // any value
)
Parameters
time
[in] Any value of datetime type.
Returned value
always false.
Price
Prohibits changes of the price coordinate.
bool Price(
double price // any value
)
Parameters
price
[in] Any value of double type.
Returned value
always false.
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChartObjectRectLabel
Class CChartObjectRectLabel is a class for simplified access to "Rectangle Label" graphic object
properties.
Description
Declaration
class CChartObjectRectLabel : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Properties
Input/output
See also
Object types, Object properties, Graphic objects
Create
Creates the "CChartObjectRectLabel" graphic object.
bool Create(
long chart_id, // Chart ID
string name, // Object name
int window, // Chart window
int X, // X coordinate
int Y, // Y coordinate
int sizeX, // Horizontal size
int sizeY // Vertical size
)
Parameters
chart_id
[in] Chart identifier (0 – current chart).
name
[in] A unique name of the object to create.
window
[in] Chart window number (0 – base window).
X
[in] X coordinate.
Y
[in] Y coordinate.
sizeX
[in] Horizontal size.
sizeY
[in] Vertical size.
Returned value
X_Size
Sets the value of "X_Size" property.
bool X_Size(
int size // Horizontal size
)
Parameters
size
[in] New horizontal size.
Returned value
Note
To get the values of "X_Size" and "Y_Size" properties use the X_Size and Y_Size methods of the
parent CChartObjectLabel class.
Y_Size
Sets the value of "Y_Size" property.
bool Y_Size(
int size // Vertical size
)
Parameters
size
[in] New vertical size.
Returned value
Note
To get the values of "X_Size" and "Y_Size" properties use the X_Size and Y_Size methods of the
parent CChartObjectLabel class.
BackColor
Gets the background color.
Returned value
Background color of the object, assigned to the class instance. If there is no object assigned, it
returns 0.
BackColor
Sets the background color.
bool BackColor(
color new_color // New color
)
Parameters
new_color
[in] New background color.
Returned value
Angle
A gag method.
bool Angle(
double angle // any value
)
Parameters
angle
[in] Any value of double type.
Returned value
Always false.
BorderType
Gets border type.
Returned value
Border type of the object, assigned to the class instance. If there is no object assigned, it returns
0.
BorderType
Sets border type.
bool BorderType(
int type // Border type
)
Parameters
type
[in] New border type.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Returned value
Type
Returns graphic object type identifier.
Returned value
CChart
Class CChart is a class for simplified access to "Chart" graphic object properties.
Description
Declaration
class CChart : public CObject
Title
<Charts\Chart.mqh>
Class Methods
General properties
Show properties
Colors properties
positions).
Properties
Navigation
Input/Output
ChartID
Returns identifier of the chart.
Returned value
Chart identifier, assigned to the class instance. If there is no object assigned, it returns -1.
Returned value
Value of "Mode" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
bool Mode(
ENUM_CHART_MODE mode // new chart mode
)
Parameters
mode
[in] Chart mode (candle, bar or line) of ENUM_CHART_MODE enumeration.
Returned value
Returned value
Value of "Foreground" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Foreground(
bool foreground // new flag value
)
Parameters
foreground
[in] New value for "Foreground" property.
Returned value
Returned value
Value of "Shift" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool Shift(
bool shift // new flag value
)
Parameters
shift
[in] New value for "Shift" property.
Returned value
Returned value
Value of "ShiftSize" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool ShiftSize(
double shift_size // new property value
)
Parameters
shift_size
[in] New value for "ShiftSize" property (in percents).
Returned value
Returned value
Value of "AutoScroll" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool AutoScroll(
bool autoscroll // new flag value
)
Parameters
autoscroll
[in] New value for "Autoscroll" property.
Returned value
Returned value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
bool Scale(
int scale // new value
)
Parameters
scale
[in] New value for "Scale" property.
Returned value
Returned value
Value of "ScaleFix" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool ScaleFix(
bool scale_fix // new value
)
Parameters
scale_fix
[in] New value for "ScaleFix" property.
Returned value
Returned value
Value of "ScaleFix_11" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool ScaleFix_11(
string scale_11 // new value
)
Parameters
scale_11
[in] New value for "ScaleFix_11" property.
Returned value
Returned value
Value of "FixedMax" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool FixedMax(
double max // new fixed maximum
)
Parameters
max
[in] New value for "FixedMax" property.
Returned value
Returned value
Value of "FixedMin" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool FixedMax(
double min // new fixed minimum
)
Parameters
max
[in] New value for "FixedMin" property.
Returned value
Returned value
Value of "PointsPerBar" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
bool PointsPerBar(
double ppb // new scale (in points per bar)
)
Parameters
ppb
[in] New value for scale (in points per bar).
Returned value
Returned value
Value of "ScalePPB" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool ScalePPB(
bool scale_ppb // new flag value
)
Parameters
scale_ppb
[in] New value for "ScalePPB" property.
Returned value
Returned value
Value of "ShowOHLC" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool ShowOHLC(
bool show // new value
)
Parameters
show
[in] New value for "ShowOHLC" property.
Returned value
Returned value
Value of "ShowLineBid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowLineBid(
bool show // new value
)
Parameters
show
[in] New value for "ShowLineBid" property.
Returned value
Returned value
Value of "ShowLineAsk" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowLineAsk(
bool show // new value
)
Parameters
show
[in] New value for "ShowLineAsk" property.
Returned value
Returned value
Value of "ShowLastLine" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowLastLine(
bool show // new flag value
)
Parameters
show
[in] New value for "ShowLastLine" property.
Returned value
Returned value
Value of "ShowPeriodSep" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowPeriodSep(
bool show // new value
)
Parameters
show
[in] New value for "ShowPeriodSep" property.
Returned value
Returned value
Value of "ShowGrid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowGrid(
bool show // new value
)
Parameters
show
[in] New value for "ShowGrid" property.
Returned value
Returned value
Value of "ShowVolumes" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowVolumes(
bool show // new value
)
Parameters
show
[in] New value for "ShowVolumes" property.
Returned value
Returned value
Value of "ShowObjectDescr" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
bool ShowObjectDescr(
bool show // New value
)
Parameters
show
[in] New value for "ShowObjectDescr" property.
Returned value
ShowDateScale
Sets new value for "ShowDateScale" property.
bool ShowDateScale(
bool show // New value
)
Parameters
show
[in] New value for "ShowDateScale" property.
Returned value
ShowPriceScale
Sets new value for "ShowPriceScale" property.
bool ShowPriceScale(
bool show // New value
)
Parameters
show
[in] New value for "ShowPriceScale" property.
Returned value
Returned value
Value of "ColorBackground" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorBackground(
color new_color // new background color
)
Parameters
new_color
[in] New background color.
Returned value
Returned value
Value of "ColorForeground" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorForeground(
color new_color // New color
)
Parameters
new_color
[in] New color for axes, scale and OHLC string.
Returned value
Returned value
Value of "ColorGrid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorGrid(
color new_color // new grid color
)
Parameters
new_color
[in] New grid color.
Returned value
Returned value
Value of "ColorBarUp" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorBarUp(
color new_color // new color for bull bars
)
Parameters
new_color
[in] New color for bull bars.
Returned value
Returned value
Value of "ColorBarDown" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorBarDown(
color new_color // new color for bear bars
)
Parameters
new_color
[in] New color for bear bars.
Returned value
Returned value
Value of "ColorCandleBull" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorCandleBull(
color new_color // new color for bull candle body
)
Parameters
new_color
[in] New color of the bull candle body.
Returned value
Returned value
Value of "ColorCandleBear" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorCandleBear(
color new_color // new color for bear candle body
)
Parameters
new_color
[in] New color of the bear candle body.
Returned value
Returned value
Value of "ColorChartLine" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorChartLine(
color new_color // new color of the chart lines
)
Parameters
new_color
[in] New color of the chart lines (Doji candles).
Returned value
Returned value
Value of "ColorVolumes" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorVolumes(
color new_color // new color of the volumes (open position levels)
)
Parameters
new_color
[in] New color of the volumes (open position levels).
Returned value
Returned value
Value of "ColorLineBid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorLineBid(
color new_color // new color for Bid line
)
Parameters
new_color
[in] New color for Bid line.
Returned value
Returned value
Value of "ColorLineAsk" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorLineAsk(
color new_color // new color for Ask line
)
Parameters
new_color
[in] New color for Ask line.
Returned value
Returned value
Value of "ColorLineLast" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorLineLast(
color new_color // new color of the last deal price line
)
Parameters
new_color
[in] New color of the last deal price line.
Returned value
Returned value
Value of "ColorStopLevels" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
bool ColorStopLevels(
color new_color // new color of the SL and TP price levels
)
Parameters
new_color
[in] New color of the Stop Loss and Take Profit price levels.
Returned value
VisibleBars
Gets total number of visible chart bars.
Returned value
Gets total number of visible bars of the chart, assigned to the class instance. If there is no chart
assigned, it returns 0.
WindowsTotal
Gets total number of chart windows, including the chart indicator subwindows.
Returned value
Total number of windows, including the chart indicator subwindows, assigned to the class instance.
If there is no chart assigned, it returns 0.
WindowIsVisible
Gets visibility flag of the specified chart subwindow.
bool WindowIsVisible(
int num // subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Returned value
Returns visibility flag of the specified chart subwindow, assigned to the chart instance. If there is
no chart assigned, it returns false.
WindowHandle
Gets window handle of the chart (HWND).
Returned value
Window handle of the chart, assigned to the chart instance. If there is no chart assigned, it returns
INVALID_HANDLE.
FirstVisibleBar
Gets the number of the first visible bar of the chart.
Returned value
Number of the first visible bar of the chart, assigned to the chart instance. If there is no chart
assigned, it returns -1.
WidthInBars
Gets window width in bars.
Returned value
Window width in chart bars, assigned to the chart instance. If there is no chart assigned, it returns
0.
WidthInPixels
Gets subwindow width in pixels.
Returned value
Subwindow width in chart pixels, assigned to the chart instance. If there is no chart assigned, it
returns 0.
HeightInPixels
Gets subwindow height in pixels.
int HeightInPixels(
int num // subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Returned value
Subwindow height in chart pixels, assigned to the chart instance. If there is no chart assigned, it
returns 0.
PriceMin
Gets minimal price of the specified subwindow.
double PriceMin(
int num // subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Returned value
Minimal price value of the chart, assigned to the class instance. If there is not chart assigned, it
returns EMPTY_VALUE.
PriceMax
Gets maximal price of the specified subwindow.
double PriceMax(
int num // subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Returned value
Maximal price value of the chart, assigned to the class instance. If there is not chart assigned, it
returns EMPTY_VALUE.
Attach
Assigns the current chart to the class instance.
void Attach()
Attach
Assigns the specified chart to the class instance.
void Attach(
long chart // Chart identifier
)
Parameters
chart
[in] Identifier of the chart to assign.
FirstChart
Assigns the first chart of the client terminal to the class instance.
void FirstChart()
NextChart
Assigns the next chart of the client terminal to the class instance.
void NextChart()
Open
Opens chart with specified parameters and assign it to the class instance.
long Open(
const string symbol_name, // Symbol name
ENUM_TIMEFRAMES timeframe // Period
)
Parameters
symbol_name
[in] Symbol name. NULL means the symbol of the current chart (to which expert attached).
timeframe
[in] Chart timeframe (ENUM_TIMEFRAMES enumeration). 0 means the current timeframe.
Returned value
Chart identifier.
Detach
Detaches chart from the class instance.
void Detach()
Close
Closes chart, assigned to the class instance.
void Close()
Navigate
Navigates the chart.
bool Navigate(
ENUM_CHART_POSITION position, // Position
int shift=0 // Shift
)
Parameters
position
[in] Value of ENUM_CHART_POSITION enumeration.
shift=0
[in] Number of bars to shift.
Returned value
Symbol
Gets symbol of the chart.
Returned value
Symbol of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
Period
Gets period of the chart.
Returned value
Period of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
Redraw
Redraws chart, assigned to the class instance.
void Redraw()
GetInteger
The function returns the value of the corresponding object property. The object property must be of
the integer type. There are 2 variants of the function.
long GetInteger(
ENUM_CHART_PROPERTY_INTEGER prop_id, // property identifier
int sub_window=0 // subwindow number
) const
2. If successful, puts the value of property to the specified variable of integer type, passed by
reference as last parameter.
bool GetInteger(
ENUM_CHART_PROPERTY_INTEGER prop_id, // property identifier
int sub_window, // subwindow number
long& value // here we get the property value
) const
Parameters
prop_id
[in] Property identifier (ENUM_CHART_PROPERTY_INTEGER enumeration).
sub_window
[in] Chart subwindow number.
value
[in] Variable of the integer type that received the value of the requested property.
Return Value
Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it
returns -1.
For the second variant the function returns true, if this property is maintained and the value has
been placed into the value variable, otherwise returns false. To read more about the error call
GetLastError().
SetInteger
Sets new value for the property of the integer type.
bool SetInteger(
ENUM_CHART_PROPERTY_INTEGER prop_id, // property identifier
long value // new value
)
Parameters
prop_id
[in] Property identifier (ENUM_CHART_PROPERTY_INTEGER enumeration).
value
[in] New value of the property.
Returned value
GetDouble
The function returns the value of the corresponding object property. The object property must be of
the double type. There are 2 variants of the function.
double GetDouble(
ENUM_CHART_PROPERTY_DOUBLE prop_id, // property identifier
int sub_window=0 // subwindow number
) const
2. If successful, puts the value of property to the specified variable of double type, passed by
reference as last parameter.
bool GetDouble(
ENUM_CHART_PROPERTY_DOUBLE prop_id, // property identifier
int sub_window, // subwindow number
double& value // here we get the property value
) const
Parameters
prop_id
[in] Property identifier (ENUM_CHART_PROPERTY_DOUBLE enumeration).
sub_window
[in] Chart subwindow number.
value
[in] Variable of the double type that received the value of the requested property.
Return Value
Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it
returns EMPTY_VALUE.
For the second variant the function returns true, if this property is maintained and the value has
been placed into the value variable, otherwise returns false. To read more about the error call
GetLastError().
SetDouble
Sets new value for the property of the double type.
bool SetDouble(
ENUM_CHART_PROPERTY_DOUBLE prop_id, // property identifier
double value // new value
)
Parameters
prop_id
[in] Property idenitifier (ENUM_CHART_PROPERTY_DOUBLE enumeration).
value
[in] New value for the property.
Returned value
GetString
The function returns the value of the corresponding object property. The object property must be of
the string type. There are 2 variants of the function.
string GetString(
ENUM_CHART_PROPERTY_STRING prop_id // property identifier
) const
2. If successful, puts the value of property to the specified variable of string type, passed by
reference as last parameter.
bool GetString(
ENUM_CHART_PROPERTY_STRING prop_id, // property identifier
string& value // here we get the property value
) const
Parameters
prop_id
[in] Property identifier (ENUM_CHART_PROPERTY_STRING enumeration).
sub_window
[in] Chart subwindow number.
value
[in] Variable of the string type that received the value of the requested property.
Return Value
Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it
returns "".
For the second variant the function returns true, if this property is maintained and the value has
been placed into the value variable, otherwise returns false. To read more about the error call
GetLastError().
SetString
Sets new value for the property of the string type.
bool SetString(
ENUM_CHART_PROPERTY_STRING prop_id, // property identifier
string value // new property value
)
Parameters
prop_id
[in] Property idenitifier (ENUM_CHART_PROPERTY_STRING enumeration).
value
[in] New value for the property.
Returned value
SetSymbolPeriod
Changes symbol and period of the chart, assigned to the class instance.
bool SetSymbolPeriod(
const string symbol_name, // Symbol
ENUM_TIMEFRAMES timeframe // Period
)
Parameters
symbol_name
[in] New symbol name. NULL means the symbol of the current chart (to which expert attached).
timeframe
[in] New chart timeframe (ENUM_TIMEFRAMES enumeration). 0 means the current timeframe.
Returned value
ApplyTemplate
Applies specified template to the chart.
bool ApplyTemplate(
const string filename // template file name
)
Parameters
filename
[in] File name of the template.
Returned value
ScreenShot
Creates screenshot of the specified chart and saves it to .gif file.
bool ScreenShot(
string filename, // File name
int width, // Width
int height, // Height
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT // Align type
) const
Parameters
filename
[in] File name for screenshot.
width
[in] Screenshot width in pixels.
height
[in] Screenshot height in pixels.
align_mode=ALIGN_RIGHT
[in] Align mode, if screenshot is narrow.
Returned value
WindowOnDropped
Gets chart subwindow number corresponding to the object (expert or script) drop point.
Returned value
Chart subwindow number of the object drop point. 0 means main chart window.
PriceOnDropped
Gets price coordinate corresponding to the object (expert or script) drop point.
Returned value
TimeOnDropped
Gets time coordinate corresponding to the object (expert or script) drop point.
Returned value
XOnDropped
Gets X coordinate corresponding to the object (expert or script) drop point.
Returned value
YOnDropped
Gets Y coordinate corresponding to the object (expert or script) drop point.
Returned value
Save
Saves object parameters to file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen(...) function.
Returned value
Load
Loads object parameters from file.
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen(...) function.
Returned value
Type
Returns graphic object type identifier.
Returned value
File Operations
This section contains the technical details of the file operations classes and descriptions of the
corresponding components of the standard MQL5 library.
The file operations classes use will save time in developing applications which uses file input/output
operations.
The MQL5 Standard Library is placed in the working directory of the terminal in the Include\Files
folder.
Class Description
CFile
CFile is a base class for CFileBin and CFileTxt classes.
Description
Class CFile provides the simplified access for all of its descendants to MQL5 API file and folder
functions.
Declaration
class CFile: public CObject
Title
#include <Files\File.mqh>
Class Methods
Attributes
Search methods
Derived classes:
CFileBin
CFileTxt
Handle
Gets file handle of the opened file.
int Handle()
Returned value
Handle of the opened file, assigned to the class instance. If there is no file assigned, it returns -1.
FileName
Gets file name of the opened file.
string FileName()
Returned value
File name of the opened file, assigned to the class instance. If there is no file assigned, it returns
"".
Flags
Gets flags of the opened file.
int Flags()
Returned value
SetUnicode
Sets/Clears the FILE_UNICODE flag.
void SetUnicode(
bool unicode // New flag value
)
Parameters
unicode
[in] New value for FILE_UNICODE flag.
Note
The result of string operations is dependent on the FILE_UNICODE flag. If it's false, the ANSI codes
are used (one byte symbols). If it set, the UNICODE codes are used (two byte symbols). If the file
has already opened, the flag cannot be changed.
SetCommon
Sets/Clears the FILE_COMMON flag.
void SetCommon(
bool common // New flag value
)
Parameters
common
[in] New value for FILE_COMMON flag.
Note
The FILE_UNICODE flag determines the current work folder. If it's false, the local terminal folder
used as the current work folder. If it's true, the general folder used as the current work folder. If the
file has already opened, the flag cannot be changed.
Open
Open the specified file and if it successful, assigns it to the class instance.
int Open(
const string file_name, // File name
int flags, // Flags
short delimiter=9 // Separator
)
Parameters
file_name
[in] File name to open.
flags
[in] File open flags.
delimiter=9
[in] CSV file separator.
Returned value
Note
The work folder is dependent on the FILE_COMMON flag, defined by SetCommon() method.
Close
Closes file, assigned to the class instance.
void Close()
Delete
Deletes the file, assigned to the file instance.
void Delete()
Delete
Deletes the specified file.
void Delete(
const string file_name // File name
)
Parameters
file_name
[in] File name of the file to delete.
Note
IsExist
Checks file for existence
bool IsExist(
const string file_name // File name
)
Parameters
file_name
[in] Name of the file to check.
Returned value
Copy
Copies a file.
bool Copy(
const string src_name, // Source file name
int src_flag, // Flag
const string dst_name, // Destination file name
int dst_flags // Flags
)
Parameters
src_name
[in] File name of the file to copy.
src_flag
[in] Flags of the file to copy (only FILE_COMMON is used).
dst_name
[in] File name of the destination file.
dst_flags
[in] Flags of the destination file (only FILE_REWRITE and FILE_COMMON are used).
Returned value
Move
Renames/moves file.
bool Move(
const string src_name, // Source file name
int src_flag, // Flag
const string dst_name, // Destination file name
int dst_flags // Flags
)
Parameters
src_name
[in] File name of the file to move.
src_flag
[in] Flags of the file to copy (only FILE_COMMON is used).
dst_name
[in] File name of the destination file.
dst_flags
[in] Flags of the destination file (only FILE_REWRITE and FILE_COMMON are used).
Returned value
Size
Gets file size in bytes.
ulong Size()
Returned value
File size in bytes. If there isn't any file assigned, it returns ULONG_MAX.
Tell
Gets the current file position.
ulong Tell()
Returned value
The current file position. If there isn't any file assigned, it returns ULONG_MAX.
Seek
Sets current file position.
void Seek(
long offset, // Offset
ENUM_FILE_POSITION origin // Origin
)
Parameters
offset
[in] File offset in bytes (can be negative).
origin
[in] Origin of the offset.
Returned value
Flush
Flushes all of the file input/output buffer data on disk.
void Flush()
IsEnding
Checks file for end. It's used during the file read operations.
bool IsEnding()
Returned value
true if end of file has been achieved after read or seek operation.
IsLineEnding
Checks file for end of line. It's used during the file read operations.
bool IsLineEnding()
Returned value
true if end of line has been achieved after the txt or csv file read operation (CR-LF chars).
FolderCreate
Creates new folder.
bool FolderCreate(
const string folder_name // Folder name
)
Parameters
folder_name
[in] Name of the folder to create. It contains path to the folder relative to the folder defined by
FILE_COMMON flag.
Returned value
Note
FolderDelete
Deletes specified folder.
bool FolderDelete(
const string folder_name // Folder name
)
Parameters
folder_name
[in] Name of the folder to delete. It contains path to the folder relative to the folder defined by
FILE_COMMON flag.
Returned value
Note
FolderClean
Cleans specified folder.
bool FolderClean(
const string folder_name // Folder name
)
Parameters
folder_name
[in] Name of the folder to delete. It contains path to the folder relative to the folder defined by
FILE_COMMON flag.
Returned value
Note
FileFindFirst
It began file search using the filter specified.
int FileFindFirst(
const string filter, // Search Filter
string& file_name // Reference to string
)
Parameters
filter
[in] Search filter.
file_name
[out] The reference to string for the first file found.
Returned value
If successful, it returns handle, that can be used for further file search using FileFindNext, or
INVALID_HANDLE if there isn't any file corresponding to the filter specified.
Note
FileFindNext
It continue search, started by function FileFindFirst().
bool FileFindNext(
int search_handle, // Search handle
string& file_name // Reference to string for the next file found
)
Parameters
search_handle
[in] Search handle, returned by FileFindFirst() method.
file_name
[in] The reference to string for the name of the file found if successful.
Returned value
true if successful, false if there isn't any file, corresponding to the filter specified.
FileFindClose
Closes search handle.
void FileFindClose(
int search_handle // Search handle
)
Parameters
search_handle
[in] Search handle, returned by FileFindFirst() method.
CFileBin
CFileBin is a class for simplified access to binary files.
Description
Declaration
class CFileBin: public CFile
Title
#include <Files\FileBin.mqh>
Class Methods
Open methods
Write methods
Read methods
Open
Open the specified binary file and if it successful, assigns it to the class instance.
int Open(
const string file_name, // File name
int flags // Flags
)
Parameters
file_name
[in] File name of the file to open.
flags
[in] File open flags (there is a forced set of the FILE_BIN flag).
Returned value
WriteChar
Writes char or uchar type variable to file.
uint WriteChar(
char value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteShort
Writes short or ushort type variable to file.
uint WriteShort(
short value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteInteger
Writes int or uint type variable to file.
uint WriteInteger(
int value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteLong
Writes long or ulong type variable to file.
uint WriteLong(
long value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteFloat
Writes float type variable to file.
uint WriteFloat(
float value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteDouble
Writes double type variable to file.
uint WriteDouble(
double value // Value
)
Parameters
value
[in] Variable to write.
Returned value
WriteString
Writes string type variable to file.
uint WriteString(
const string value // Value
)
Parameters
value
[in] String to write.
Returned value
WriteString
Writes string type variable to file.
uint WriteString(
const string value, // Value
int size // Size
)
Parameters
value
[in] String to write.
size
[in] Number of bytes to write.
Returned value
WriteCharArray
Writes an array of char or uchar type variables to file.
uint WriteCharArray(
char& array[], // Array reference
int start_item=0, // Start element
int items_count=-1 // Number of elements
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteShortArray
Writes an array of short or ushort type variables to file.
uint WriteShortArray(
short& array[], // Array to write
int start_item=0, // Start element
int items_count=-1 // Number of elements to write
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteIntegerArray
Writes an array of int or uint type variables to file.
uint WriteIntegerArray(
int& array[], // Array to write
int start_item=0, // Start element
int items_count=-1 // Number of elements to write
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteLongArray
Writes an array of long or ulong type variables to file.
uint WriteLongArray(
long& array[], // Array to write
int start_item=0, // Start element
int items_count=-1 // Number of elements to write
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteFloatArray
Writes an array of float type variables to file.
uint WriteFloatArray(
float& array[], // Array to write
int start_item=0, // Start element
int items_count=-1 // Number of elements to write
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteDoubleArray
Writes an array of double type variables to file.
uint WriteDoubleArray(
double& array[], // Array to write
int start_item=0, // Start element
int items_count=-1 // Number of elements to write
)
Parameters
array[]
[in] Array to write.
start_item=0
[in] Start element to write from.
items_count=-1
[in] Number of elements to write (-1 - for whole array).
Returned value
WriteObject
Writes data of the CObject class inheritor instance to file.
bool WriteObject(
CObject* object // Reference to the object
)
Parameters
object
[in] Reference to the CObject class inheritor instance to write.
Returned value
ReadChar
Reads char or uchar type variable from file.
bool ReadChar(
char& value // Target variable
)
Parameters
value
[in] Target variable of type char.
Returned value
ReadShort
Reads short or ushort type variable from file.
bool ReadShort(
short& value
)
Parameters
value
[in] Target variable of type short or ushort.
Returned value
ReadInteger
Reads int or uint type variable from file.
bool ReadInteger(
int& value // Target variable
)
Parameters
value
[in] Target variable of type int or uint.
Returned value
ReadLong
Reads long or ulong type variable from file.
bool ReadLong(
long& value
)
Parameters
value
[in] Target variable of type long or ulong.
Returned value
ReadFloat
Reads float type variable from file.
bool ReadFloat(
float& value // Target variable
)
Parameters
value
[in] Target variable of type float.
Returned value
ReadDouble
Reads double type variable from file.
bool ReadDouble(
double& value
)
Parameters
value
[in] Target variable of type double.
Returned value
ReadString
Reads string type variable from file.
bool ReadString(
string& value // Target string
)
Parameters
value
[in] Target variable of type string.
Returned value
ReadString
Reads string type variable from file.
bool ReadString(
string& value
)
Parameters
value
[in] Target variable of type string.
Returned value
ReadCharArray
Reads an array of char or uchar type variables from file.
bool ReadCharArray(
char& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type char or uchar.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadShortArray
Reads an array of short or ushort type variables from file.
bool ReadShortArray(
short& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type short or ushort.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadIntegerArray
Reads an array of int or uint type variables from file.
bool ReadIntegerArray(
int& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type int or uint.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadLongArray
Reads an array of long or ulong type variables from file.
bool ReadLongArray(
long& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type long or ulong.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadFloatArray
Reads an array of float type variables from file.
bool ReadFloatArray(
float& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type float.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadDoubleArray
Reads an array of double type variables from file.
bool ReadDoubleArray(
double& array[], // Target array
int start_item=0, // Start element
int items_count=-1 // Number of elements to read
)
Parameters
array[]
[in] Reference to the target array of type double.
start_item=0
[in] Start element to read from.
items_count=-1
[in] Number of elements to read (-1 - read to the end of file).
Returned value
ReadObject
Reads data of the CObject class inheritor instance from file.
bool ReadObject(
CObject* object // Reference to the object
)
Parameters
object
[in] Reference to the target CObject class inheritor instance for read to.
Returned value
CFileTxt
CFileTxt is a class for simplified access to text files.
Description
Declaration
class CFileTxt: public CFile
Title
#include <Files\FileTxt.mqh>
Class Methods
Open methods
Write methods
Read methods
Open
Open the specified text file and if it successful, assigns it to the class instance.
int Open(
const string file_name, // file name
int flags // flags
)
Parameters
file_name
[in] File name to open.
flags
[in] File open flags (there is a forced set of the FILE_TXT flag).
Returned value
WriteString
Writes string type variable to file.
uint WriteString(
const string value // String to write
)
Parameters
value
[in] String to write.
Returned value
ReadString
Reads string type variable from file.
string ReadString()
Returned value
String operations
This section contains the technical details of the string operations classes and descriptions of the
corresponding components of the standard MQL5 library.
The use of string operations classes will save time in developing applications which uses text
processing operations.
The MQL5 Standard Library is placed in the working directory of the terminal in the Include\Strings
folder.
Class Description
CString
CString is a class for simplified access to the variables of string type.
Description
Class CFile provides the simplified access for all of its descendants to MQL5 API string functions.
Declaration
class CString: public CObject
Title
#include <Strings\String.mqh>
Class Methods
Fill methods
Compare methods
Substring methods
Trim/delete methods
Convert methods
Search methods
Str
Gets a string.
Returned value
Copy of a string.
Len
Gets length of a string.
Returned value
Length of a string.
Copy
Copies a string by reference.
void Copy(
string& copy // Reference
) const;
Parameters
copy
[in] Reference to a string to copy.
Copy
Copies a string to the CString class instance.
void Copy(
CString* copy // Object descriptor
) const;
Parameters
copy
[in] CString class object descriptor.
Fill
Fills a string with specified char.
bool Fill(
short character // Character
)
Parameters
character
[in] Character for filling.
Returned value
Assign
Assigns a string.
void Assign(
const string str // String to assign
)
Parameters
str
[in] String to assign.
Assign
Assigns a string to the CString class instance.
void Assign(
CString* str // Object descriptor
)
Parameters
str
[in] CString class object descriptor to assign.
Append
Appends a string.
void Append(
const string str // String to append
)
Parameters
str
[in] String to append.
Append
Appends a string to the CString class instance.
void Append(
CString* string // Object descriptor
)
Parameters
string
[in] CString class object descriptor to append.
Insert
Inserts a string to the specified position.
uint Insert(
uint pos, // Position
const string str // String to insert
)
Parameters
pos
[in] Insert position.
str
[in] String to insert.
Returned value
Insert
Inserts a string to the specified position to the CString class instance.
uint Insert(
uint pos, // Position
CString* str // Object descriptor
)
Parameters
pos
[in] Insert position.
str
[in] CString class object descriptor to insert.
Returned value
Compare
Compares a string.
int Compare(
const string str // String to compare
) const;
Parameters
str
[in] String to compare.
Returned value
I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if
the class string greater than a string to compare.
Compare
Compares a string with a string of the CString class instance.
int Compare(
CString* str // Object descriptor
) const;
Parameters
str
[in] CString class object descriptor to compare.
Returned value
I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if
the class string greater than a string to compare.
CompareNoCase
Compares a strings case insensitive.
int CompareNoCase(
const string str // String to compare
) const;
Parameters
str
[in] String to compare.
Returned value
I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if
the class string greater than a string to compare.
CompareNoCase
Compares a string (case insensitive) with a string of the CString class instance.
int CompareNoCase(
CString* str // Object descriptor
) const;
Parameters
str
[in] CString class object descriptor to compare.
Returned value
I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if
the class string greater than a string to compare.
Left
Gets a specified number of characters from the left side of a string.
string Left(
uint count // Number of characters
)
Parameters
count
[in] Number of characters.
Returned value
Resulted substring.
Right
Gets a specified number of characters from the right side of a string.
string Right(
uint count // Number of characters
)
Parameters
count
[in] Number of characters.
Returned value
Resulted substring.
Mid
Gets a specified number of characters from a string.
string Mid(
uint pos, // Position
uint count // Number of characters
)
Parameters
pos
[in] Position of a string.
count
[in] Number of characters.
Returned value
Resulted substring.
Trim
Removes all leading and trailing occurrences of a set of specified characters (and ' ','\t','\r','\n') from a
string.
int Trim(
const string targets // Set of characters to remove
)
Parameters
targets
[in] Set of characters to remove.
Returned value
Example:
TrimLeft
Removes all leading occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimLeft(
const string targets // Set of characters to remove
)
Parameters
targets
[in] Set of characters to remove.
Returned value
TrimRight
Removes all trailing occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimRight(
const string targets // Set of characters to remove
)
Parameters
targets
[in] Set of characters to remove.
Returned value
Clear
Clears a string.
bool Clear()
Returned value
ToUpper
Converts a string to uppercase.
bool ToUpper()
Returned value
ToLower
Converts a string to lowercase.
bool ToLower()
Returned value
Reverse
Reverses of a string.
void Reverse()
Find
Searches for the first match of a substring.
int Find(
uint start, // Position
const string substring // Substring to search for
) const;
Parameters
start
[in] The index of the character in the string to begin the search with, or 0 to start from the
beginning.
substring
[in] Substring to search for.
Returned value
The index of the first character that matches the requested substring; -1 if the substring is not
found.
FindRev
Searches for the last match of a substring.
int FindRev(
const string substring // Substring
) const;
Parameters
substring
[in] A substring to search for.
Returned value
The index of the last character that matches the requested substring; -1 if the substring is not
found.
Remove
Deletes a substring from a string.
uint Remove(
const string substring // Substring to remove
)
Parameters
substring
[in] A substring to search for.
Returned value
Replace
Replaces a substring from a string.
uint Replace(
const string substring, // Substring to replace
const string newstring // New substring
)
Parameters
substring
[in] A substring to search for.
newstring
[in] A substring to replace for.
Returned value
The use of the technical indicator and timeseries classes will save time in developing applications
(scripts, Expert Advisors).
The MQL5 Standard Library is placed in the working directory of the terminal in the Include\Indicators
folder.
Class/group Description
Class/group Description
CSpreadBuffer
CSpreadBuffer is a class for simplified access to spreads of the bars in the history.
Description
The CSpreadBuffer class provides an access to spreads of the bars in the history.
Declaration
class CSpreadBuffer: public CArrayInt
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes
Settings
Size
Sets buffer size.
void Size(
int size // new size
)
Parameters
size
[in] New buffer size.
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
At
Gets the buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CTimeBuffer
CTimeBuffer is a class for simplified access to opening times of the bars in the history.
Description
The CTimeBuffer class provides an access to opening times of the bars in the history.
Declaration
class CTimeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes
Settings
Size
Sets buffer size.
void Size(
int size // new size
)
Parameters
size
[in] New buffer size.
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
At
Gets the buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CTickVolumeBuffer
CTickVolumeBuffer is a class for simplified access to tick volumes of bars in the history.
Description
The CTickVolumeBuffer class provides an access to tick volumes of bars in the history.
Declaration
class CTickVolumeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes
Settings
Size
Sets buffer size.
void Size(
int size // new size
)
Parameters
size
[in] New buffer size.
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
At
Gets the buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CRealVolumeBuffer
CRealVolumeBuffer is a class for simplified access to real volumes of bars in the history.
Description
The CTickVolumeBuffer class provides an access to real volumes of bars in the history.
Declaration
class CRealVolumeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes
Settings
Size
Sets buffer size.
void Size(
int size // new size
)
Parameters
size
[in] New buffer size.
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
At
Gets the buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CDoubleBuffer
CDoubleBuffer is a base class for simplified access to data buffers of double type.
Description
The CDoubleBuffer class provides an access to the data of the buffer of double type.
Declaration
class CDoubleBuffer: public CArrayDouble
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes
Settings
Size
Sets buffer size.
void Size(
int size // new size
)
Parameters
size
[in] New buffer size.
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
At
Gets the buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
Minimum
Gets index of the lowest element of the buffer in the specified range.
int Minimum(
int start, // starting index
int count // number of elements to proceed
) const
Parameters
start
[in] Starting index of the array.
count
[in] Number of elements to proceed.
Returned value
Maximum
Gets index of the highest element of the buffer in the specified range.
int Maximum(
int start, // starting index
int count // number of elements to proceed
) const
Parameters
start
[in] Starting index of the array.
count
[in] Number of elements to proceed.
Returned value
COpenBuffer
COpenBuffer is a class for simplified access to open prices of bars in the history.
Description
The COpenBuffer class provides an access to open prices of bars in the history.
Declaration
class COpenBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CHighBuffer
CHighBuffer is a class for simplified access to high prices of bars in the history.
Description
The CHighBuffer class provides an access to high prices of bars in the history.
Declaration
class CHighBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CLowBuffer
CLowBuffer is a class for simplified access to low prices of bars in the history.
Description
The CLowBuffer class provides an access to low prices of bars in the history.
Declaration
class CLowBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CCloseBuffer
CCloseBuffer is a class for simplified access to close prices of bars in the history.
Description
The CCloseBuffer class provides an access to close prices of bars in the history.
Declaration
class CCloseBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Refresh
Updates the buffer.
Returned value
RefreshCurrent
Updates the current (zeroth) element of the buffer.
Returned value
CIndicatorBuffer
CIndicatorBuffer is a class for simplified access to the data of the indicator's buffer.
Description
The CIndicatorBuffer class provides the simplified access to the data buffer of technical indicator.
Declaration
class CIndicatorBuffer: public CDoubleBuffer
Title
#include <Indicators\Indicator.mqh>
Class Methods
Attributes
Offset
Gets offset of the buffer.
Returned value
Buffer offset.
Offset ()
Sets offset of the buffer.
void Offset(
int offset // offset
)
Parameters
offset
[in] New buffer offset.
Name
Gets the name of the buffer.
Returned value
Name
Sets the name of the buffer.
void Name(
string name // name
)
Parameters
name
[in] New name of the buffer.
At
Gets buffer element by index.
long At(
int index // index
)
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the whole buffer.
bool Refresh(
int handle, // handle
int num // buffer number
)
Parameters
handle
[in] Handle of the indicator.
num
[in] Buffer index of the indicator.
Returned value
RefreshCurrent
Updates the current (zeroth) buffer element.
bool RefreshCurrent(
int handle, // handle of the indicator
int num // buffer number
)
Parameters
handle
[in] Handle of the indicator.
num
[in] Buffer number.
Returned value
CSeries
CSeries is a base class for an access to the timeseries data of the Standard Library.
Description
The CSeries class provides the simplified access to MQL5 timeseries functions to all its descendants.
Declaration
class CSeries: public CArrayObj
Title
#include <Indicators\Series.mqh>
Class Methods
Attributes
Name
Gets the name of timeseries or indicator
Returned value
BuffersTotal
Gets the number of buffers of timeseries or indicator.
Returned value
Note
Timeframe
Gets the timeframe flag of timeseries or indicator.
Returned value
Note
Symbol
Gets the symbol of timeseries or indicator.
Returned value
Period
Gets the period of timeseries or indicator.
Returned value
RefreshCurrent
Sets a flag to update the current values of timeseries or indicator.
string RefreshCurrent(
bool flag // new flag
)
Parameters
flag
[in] New flag.
Returned value
None.
BufferResize
Sets buffer size of timeseries or indicator.
Parameters
size
[in] New size of the buffers.
Note
Refresh
Updates the data of timeseries or indicator.
Parameters
flags
[in] Timeframes to update (flag).
PeriodDescription
Gets the string representation of the specified ENUM_TIMEFRAMES enumeration.
string PeriodDescription(
int val==0 // value
) const
Parameters
val==0
[in] Value to convert.
Returned value
Note
If the value isn't specified or equal to zero, it returns the timeframe of timeseries or indicator.
CPriceSeries
CPriceSeries is a base class for access to the price data.
Description
The CSeries class provides the simplified access to MQL5 functions for working with price data to all
its descendants.
Declaration
class CPriceSeries: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
BufferResize
Sets new size of the buffer.
Parameters
size
[in] New buffer size.
GetData
Gets the specified buffer element by index.
Parameters
index
[in] Index of buffer element.
Returned value
Refresh
Updates the timeseries data
Parameters
flags
[in] Timeframes to update (flag).
MinIndex
Gets the index of minimal element in the specified range.
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
Returned value
The index of minimal element in the specified range, or -1 in the case of error.
MinValue
Gets the value and index of minimal element in the specified range.
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of integer type.
Returned value
The value of minimal element of the buffer in the specified range, or EMPTY_VALUE if error.
Note
MaxIndex
Gets the index of maximal element in the specified range.
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
Returned value
The index of the maximal element in the specified range, or -1 in the case of error.
MaxValue
Gets the value and index of maximal element in the specified range.
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of integer type.
Returned value
The value of maximal element of the buffer in the specified range, or EMPTY_VALUE if error.
Note
CIndicator
CIndicator is a base class for technical indicator classes of the standard MQL Library.
Description
The CIndicator class provides the simplified access for all of its descendants to MQL5 API technical
indicator functions.
Declaration
class CIndicator: public CSeries
Title
#include <Indicators\Indicator.mqh>
Class Methods
Attributes
Creation
Conversion of Enumerations
Derived classes:
CiAC
CiAD
CiADX
CiADXWilder
CiAlligator
CiAMA
CiAO
CiATR
CiBands
CiBearsPower
CiBullsPower
CiBWMFI
CiCCI
CiChaikin
CiDEMA
CiDeMarker
CiEnvelopes
CiForce
CiFractals
CiFrAMA
CiGator
CiIchimoku
CiMA
CiMACD
CiMFI
CiMomentum
CiOBV
CiOsMA
CiRSI
CiRVI
CiSAR
CiStdDev
CiStochastic
CiTEMA
CiTriX
CiVIDyA
CiVolumes
CiWPR
Handle
Gets the indicator's handle.
Returned value
Status
Gets the status of the indicator.
Returned value
FullRelease
Sets a flag to release the handle of the indicator.
void FullRelease(
bool flag // flag
)
Parameters
flag
[in] New value of the handle release flag.
Create
Creates the indicator with specified parameters.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period, // period
ENUM_INDICATOR type, // type
int num_params, // number of parameters
MqlParam& params // reference to the parameters array
)
Parameters
symbol
[in] Symbol name.
period
[in] Period (ENUM_TIMEFRAMES enumeration).
type
[in] Indicator's type (ENUM_INDICATOR enumeration).
num_params
[in] Number of indicator's parameters.
params
[in] Reference to the parameters array for the indicator.
Returned value
BufferResize
Sets the size of the indicator's buffer.
void BufferResize(
int size // new size
)
Parameters
size
[in] New buffer size.
Note
GetData
Gets the specified element from the specified buffer of the indicator.
double GetData(
int buffer_num, // buffer number
int index // element index
) const
Parameters
buffer_num
[in] Buffer number.
index
[in] Element index.
Returned value
GetData
Gets the data from the indicator's buffer by starting position and number of necessary data.
int GetData(
int start_pos, // position
int count, // number of elements needed
int buffer_num, // buffer number
double& buffer // target array for data
) const
Parameters
start_pos
[in] Starting position of the indicator's buffer.
count
[in] Number of elements needed.
buffer_num
[in] Number of the indicator's buffer.
buffer
[in] Referencet to the target array for the data.
Returned value
GetData
Gets the data from the indicator's buffer by start time and number of necessary data.
int GetData(
datetime start_time, // starting time
int count, // number of elements needed
int buffer_num, // buffer number
double& buffer // target array for data
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer_num
[in] Number of the indicator's buffer.
buffer
[in] Reference to the target array.
Returned value
GetData
Gets the data from the indicator's buffer by start and stop time and number of necessary data.
int GetData(
datetime start_time, // start time
datetime stop_time, // stop time
int buffer_num, // number of buffer
double& buffer // target array for data
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer_num
[in] Number of the indicator's buffer.
buffer
[in] Reference to the target array.
Returned value
Refresh
Updates the indicator's data.
void Refresh(
int flags // flags
)
Parameters
flags
[in] Timeframe update flags.
Minimum
Returns the index of minimal element of the specified buffer in a specified range.
int Minimum(
int buffer_num, // buffer number
int start, // starting index
int count // number of elements to proceed
) const
Parameters
buffer_num
[in] Buffer number to search the value in.
start
[in] Starting index of the search.
count
[in] Number of elements to search.
Returned value
MinValue
Returns the value and index of minimal element of the specified buffer in a specified range.
double MinValue(
int buffer_num, // buffer number
int start, // starting index
int count, // number of elements to proceed
int& index // reference
) const
Parameters
buffer_num
[in] Buffer number to search the value in.
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of int type for the minimal element index.
Returned value
The value of the minimal element of the specified buffer in a specified range.
Note
The index of minimal buffer element is stored into the variable index, passed by reference.
Maximum
Returns the index of maximal element of the specified buffer in a specified range.
int Maximum(
int buffer_num, // buffer number
int start, // starting index
int count // number of elements to proceed
) const
Parameters
buffer_num
[in] Buffer number to search the value in.
start
[in] Starting index of the search.
count
[in] Number of elements to search.
Returned value
MaxValue
Returns the value and index of maximal element of the specified buffer in a specified range.
double MaxValue(
int buffer_num, // buffer number
int start, // starting index
int count, // number of elements to proceed
int& index // reference
) const
Parameters
buffer_num
[in] Buffer number to search the value in.
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of int type for the maximal element index.
Returned value
The value of the maximal element of the specified buffer in a specified range.
Note
The index of maximal buffer element is stored into the variable index, passed by reference.
MethodDescription
The function returns the value of ENUM_MA_METHOD enumeration as a string.
string MethodDescription(
int val==0 // value
) const
Parameters
val==0
[in] Value of ENUM_MA_METHOD enumeration.
Returned value
PriceDescription
The method returns the value of ENUM_APPLIED_PRICE enumeration as a string.
string PriceDescription(
int val==0 // value
) const
Parameters
val==0
[in] Value of ENUM_APPLIED_PRICE enumeration.
Returned value
VolumeDescription
The method returns the value of ENUM_APPLIED_VOLUME enumeration as a string.
string VolumeDescription(
int val==0 // value
) const
Parameters
val==0
[in] Value of ENUM_APPLIED_VOLUME enumeration.
Returned value
CIndicators
The CIndicators is a class for collecting instances of timeseries and technical indicators classes.
Description
The CIndicators class provides creation of the technical indicators class instances, their storage and
management (data synchronization, handle and memory management).
Declaration
class CIndicators: public CArrayObj
Title
#include <Indicators\Indicators.mqh>
Class Methods
Create Methods
Create
It creates the indicator with the specified parameters.
CIndicator* Create(
string symbol, // Symbol name
ENUM_TIMEFRAMES period, // Period
ENUM_INDICATOR type, // Indicator's type
int count, // Number of parameters
MqlParam& params // Parameters array reference
)
Parameters
symbol
[in] Symbol name.
period
[in] Period (ENUM_TIMEFRAMES enumeration).
type
[in] Indicator's type (ENUM_INDICATOR).
count
[in] Number of parameters for the indicator.
params
[in] Reference to the parameters array for the indicator.
Returned value
If successful, it returns the reference to the created indicator, and NULL if the indicator hasn't been
created.
Refresh
Updates data for all technical indicators in the collection.
int Refresh()
Returned value
Timeseries classes
This group of chapters contains technical details of timeseries classes of the MQL5 Standard Library
and descriptions of all its key components.
Class Description
CiSpread
CiSpread is a class designed for access to spreads of the bars in the history.
Description
Declaration
class CiSpread: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the spreads history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
BufferResize
Sets new size of the series.
Parameters
size
[in] New buffer size.
GetData
Gets the element of timeseries by index.
int GetData(
int index // index
) const
Parameters
index
[in] Index of the element needed.
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
int& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
int& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
int& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
Refresh
Updates the data of timeseries.
Parameters
flags
[in] Timeframe flags.
CiTime
CiTime is a class designed for access to open times of the bars in the history.
Description
The CiTime class provides an access to open times of the bars in the history.
Declaration
class CiTime: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the opening times of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
BufferResize
Sets new size of the series.
Parameters
size
[in] New buffer size.
GetData
Gets the element of timeseries by index.
datetime GetData(
int index // index
) const
Parameters
index
[in] Index of the element needed.
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
long& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
Refresh
Updates the data of timeseries.
Parameters
flags
[in] Timeframe flags.
CiTickVolume
CiTickVolume is a class designed for access to tick volumes of the bars in the history.
Description
The CiTickVolume class provides an access to tick volumes of the bars in the history.
Declaration
class CiTickVolume: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the tick volumes of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
BufferResize
Sets new size of the series.
Parameters
size
[in] New buffer size.
GetData
Gets the element of timeseries by index.
datetime GetData(
int index // index
) const
Parameters
index
[in] Index of the element needed.
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
long& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
Refresh
Updates the data of timeseries.
Parameters
flags
[in] Timeframe flags.
CiRealVolume
CiRealVolume is a class designed for access to real volumes of the bars in the history.
Description
The CiRealVolume class provides an access to real volumes of the bars in the history.
Declaration
class CiRealVolume: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the real volumes of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
BufferResize
Sets new size of the series.
Parameters
size
[in] New buffer size.
GetData
Gets the element of timeseries by index.
datetime GetData(
int index // index
) const
Parameters
index
[in] Index of the element needed.
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
long& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
long& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
Refresh
Updates the data of timeseries.
Parameters
flags
[in] Timeframe flags.
CiOpen
CiOpen is a class designed for access to open prices of the bars in the history.
Description
The CiOpen class provides an access to open prices of the bars in the history.
Declaration
class CiOpen: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the open prices of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
double& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
CiHigh
CiHigh is a class designed for access to high prices of the bars in the history.
Description
The CiHigh class provides an access to high prices of the bars in the history.
Declaration
class CiHigh: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the high prices of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
double& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
CiLow
CiLow is a class designed for access to low prices of the bars in the history.
Description
The CiLow class provides an access to low prices of the bars in the history.
Declaration
class CiLow: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the low prices of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
double& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
CiClose
CiClose is a class designed for access to close prices of the bars in the history.
Description
The CiClose class provides an access to close prices of the bars in the history.
Declaration
class CiClose: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries with the specified parameters for access to the closing prices of the bars in the
history.
bool Create(
string symbol, // symbol
ENUM_TIMEFRAMES period // period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int start_pos, // starting position
int count, // number of elements to get
double& buffer // target array
) const
Parameters
start_pos
[in] Starting position of timeseries.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for the data.
Returned value
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time, // starting time
int count, // number of elements
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Returned value
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time, // starting time
datetime stop_time, // stop time
double& buffer // target array
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Returned value
Class/group Description
CiEnvelopes Envelopes
CiADX
CiADX is a class intended for using the Average Directional Index technical indicator.
Description
The CiADX class provides the creation and access to the data of the Average Directional Index
indicator.
Declaration
class CiADX: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
Type
Returns the object type identifier.
Returned value
CiADXWilder
CiADXWilder is a class intended for using the Average Directional Index by Welles Wilder technical
indicator.
Description
The CiADXWilder class provides the creation and access to the data of the Average Directional Index
by Welles Wilder indicator.
Declaration
class CiADXWilder: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
Type
Returns the object type identifier.
Returned value
CiBands
CiBands is a class intended for using the Bollinger Bands technical indicator.
Description
The CiBands class provides the creation and access to the data of the Bollinger Bands indicator.
Declaration
class CiBands: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
MaShift
Returns the horizontal shift of the indicator.
Returned value
Deviation
Returns the deviation.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Shift
double deviation, // Deviation
int applied // applied price, or handle
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift of the indicator.
deviation
[in] Deviation.
applied
[in] Volume type to apply.
Returned value
Base
Returns the buffer element of the base line by the specified index.
double Base(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the Base line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Upper
Returns the buffer element of the upper line by the specified index.
double Upper(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Lower
Returns the buffer element of the lower line by the specified index.
double Lower(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiEnvelopes
CiEnvelopes is a class intended for using the Envelopes technical indicator.
Description
The CiEnvelopes class provides the creation and access to the data of the Envelopes indicator.
Declaration
class CiEnvelopes: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
MaShift
Returns the horizontal shift of the indicator.
Returned value
MaMethod
Returns the averaging method.
Returned value
Deviation
Returns the value of deviation.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_MA_METHOD ma_method, // Averaging method
int applied, // Price type or handle to apply
double deviation // Deviation
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Price type of handle to apply.
deviation
[in] Deviation.
Returned value
Upper
Returns the buffer element of the upper line by the specified index.
double Upper(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Lower
Returns the buffer element of the lower line by the specified index.
double Lower(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiIchimoku
CiIchimoku is a class intended for using the Ichimoku Kinko Hyo technical indicator.
Description
The CiIchimoku class provides the creation, setup and access to the data of the Ichimoku Kinko Hyo
indicator.
Declaration
class CiIchimoku: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
TenkanSenPeriod
Returns the TenkanSen period.
Returned value
KijunSenPeriod
Returns the KijunSen period.
Returned value
SenkouSpanBPeriod
Returns the SenkouSpanB period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int tenkan_sen, // Period of TenkanSen
int kijun_sen, // Period of KijunSen
int senkou_span_b // Period of SenkouSpanB
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
tenkan_sen
[in] Period of TenkanSen.
kijun_sen
[in] Period of KijunSen.
senkou_span_b
[in] Period of SenkouSpanB.
Returned value
TenkanSen
Returns the buffer element of the TenkanSen line by the specified index.
double TenkanSen(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the TenkanSen line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
KijunSen
Returns the buffer element of the KijunSen line by the specified index.
double KijunSen(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the KijunSen line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
SenkouSpanA
Returns the buffer element of the SenkouSpanA line by the specified index.
double SenkouSpanA(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the SenkouSpanA line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
SenkouSpanB
Returns the buffer element of the SenkouSpanB line by the specified index.
double SenkouSpanB(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the SenkouSpanB line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
ChinkouSpan
Returns the buffer element of the ChinkouSpan line by the specified index.
double ChinkouSpan(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the ChinkouSpan line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
Type
Returns the object type identifier.
Returned value
CiMA
CiMA is a class intended for using the Moving Average technical indicator.
Description
The CiMA class provides the creation, setup and access to the data of the Moving Average indicator.
Declaration
class CiMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
MaShift
Returns the horizontal shift of the indicator.
Returned value
MaMethod
Returns the averaging method.
Returned value
Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator
creation.
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string string, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_MA_METHOD ma_method, // Averaging method
int applied // Price type of handle to apply
)
Parameters
string
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiSAR
CiSAR is a class intended for using the Parabolic Stop And Reverse System technical indicator.
Description
The CiSAR class provides the creation, setup and access to the data of the Parabolic Stop And Reverse
System indicator.
Declaration
class CiSAR: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
SarStep
Returns the step for the velocity increasing (acceleration coefficient).
Returned value
The step for the velocity increasing, defined at the indicator creation.
Maximum
Returns the coefficient of price following.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
double step, // Step
double maximum // Coefficient
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
step
[in] Step for the velocity increasing.
maximum
[in] Price following coefficient.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiStdDev
CiStdDev is a class intended for using the Standard Deviation technical indicator.
Description
The CiStdDev class provides the creation, setup and access to the data of the Standard Deviation
indicator.
Declaration
class CiStdDev: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
MaShift
Returns the horizontal shift of the indicator.
Returned value
MaMethod
Returns the averaging method.
Returned value
Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator
creation.
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_MA_METHOD ma_method, // Averaging method
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiDEMA
CiDEMA is a class intended for using the Double Exponential Moving Average technical indicator.
Description
The CiDEMA class provides the creation, setup and access to the data of the Double Exponential
Moving Average indicator.
Declaration
class CiDEMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
IndShift
Returns the horizontal shift of the indicator.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string string, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ind_shift, // Shift
int applied // Price type of handle to apply
)
Parameters
string
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ind_shift
[in] Horizontal shift.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiTEMA
CiTEMA is a class intended for using the Triple Exponential Moving Average technical indicator.
Description
The CiTEMA class provides the creation, setup and access to the data of the Triple Exponential Moving
Average indicator.
Declaration
class CiTEMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
IndShift
Returns the horizontal shift of the indicator.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Offset
int applied // Price type of handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiFrAMA
CiFrAMA is a class intended for using the Fractal Adaptive Moving Average technical indicator.
Description
The CiFrAMA class provides the creation, setup and access to the data of the Fractal Adaptive Moving
Average indicator.
Declaration
class CiFrAMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
IndShift
Returns the horizontal shift of the indicator.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Offset
int applied // Price type of handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_shift
[in] Horizontal shift.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiAMA
CiAMA is a class intended for using the Adaptive Moving Average technical indicator.
Description
The CiAMA class provides the creation, setup and access to the data of the Adaptive Moving Average
indicator.
Declaration
class CiAMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
FastEmaPeriod
Returns the averaging period for the fast EMA.
Returned value
Returns the averaging period for the fast EMA, defined at the indicator creation.
SlowEmaPeriod
Returns the averaging period for the slow EMA.
Returned value
Returns the averaging period for the slow EMA, defined at the indicator creation.
IndShift
Returns the horizontal shift of the indicator.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string string, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int fast_ema_period, // Fast EMA period
int slow_ema_period, // Slow EMA period
int ind_shift, // Shift
int applied // Price type or handle to apply
)
Parameters
string
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
fast_ema_period
[in] Fast EMA averaging period.
slow_ema_period
[in] Slow EMA averaging period.
ind_shift
[in] Horizontal shift.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiVIDyA
CiVIDyA is a class intended for using the Variable Index DYnamic Average technical indicator.
Description
The CiVIDyA class provides the creation, setup and access to the data of the Variable Index DYnamic
Average indicator.
Declaration
class CiVIDyA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes
Create Methods
Input/output
CmoPeriod
Returns the period for Momentum.
Returned value
EmaPeriod
Returns the averaging period for EMA.
Returned value
Returns the averaging period for EMA, defined at the indicator creation.
IndShift
Returns the horizontal shift of the indicator.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int cmo_period, // Momentum period
int ema_period, // Averaging period
int ind_shift, // Shift
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
cmo_period
[in] Momentum period.
ema_period
[in] Averaging period.
ind_shift
[in] Horizontal shift.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
Oscillators
This group of chapters contains the technical details of Oscillators classes of the MQL5 Standard
Library and descriptions of all its key components.
Class/group Description
CiDeMarker DeMarker
CiMomentum Momentum
CiATR
CiATR is a class intended for using the Average True Range technical indicator.
Description
The CiATR class provides the creation, setup and access to the data of the Average True Range
indicator.
Declaration
class CiATR: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiBearsPower
CiBearsPower is a class intended for using the Bears Power technical indicator.
Description
The CiBearsPower class provides the creation, setup and access to the data of the Bears Power
indicator.
Declaration
class CiBearsPower: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiBullsPower
CiBullsPower is a class intended for using the Bulls Power technical indicator.
Description
The CiBullsPower class provides the creation, setup and access to the data of the Bulls Power
indicator.
Declaration
class CiBullsPower: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiCCI
CiCCI is a class intended for using the Commodity Channel Index technical indicator.
Description
The CiCCI class provides the creation, setup and access to the data of the Commodity Channel Index
indicator.
Declaration
class CiCCI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiChaikin
CiChaikin is a class intended for using the Chaikin Oscillator technical indicator.
Description
The CiChaikin class provides the creation, setup and access to the data of the Chaikin Oscillator
indicator.
Declaration
class CiChaikin: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
FastMaPeriod
Returns the averaging period for the fast EMA.
Returned value
Returns the averaging period for the fast EMA, defined at the indicator creation.
SlowMaPeriod
Returns the averaging period for the slow EMA.
Returned value
Returns the averaging period for the slow EMA, defined at the indicator creation.
MaMethod
Returns the averaging method.
Returned value
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int fast_ma_period, // Fast EMA period
int slow_ma_period, // Slow EMA period
ENUM_MA_METHOD ma_method, // Averaging method
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
fast_ma_period
[in] Period for fast EMA.
slow_ma_period
[in] Period for slow EMA.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiDeMarker
CiDeMarker is a class intended for using the DeMarker technical indicator.
Description
The CiDeMarker class provides the creation, setup and access to the data of the DeMarker indicator.
Declaration
class CiDeMarker: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiForce
CiForce is a class intended for using the Force Index technical indicator.
Description
The CiForce class provides the creation, setup and access to the data of the Force Index indicator.
Declaration
class CiForce: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
MaMethod
Returns the averaging method.
Returned value
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_MA_METHOD ma_method, // Averaging method
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiMACD
CiMACD is a class intended for using the Moving Averages Convergence-Divergence technical
indicator.
Description
The CiMACD class provides the creation, setup and access to the data of the Moving Averages
Convergence-Divergence indicator.
Declaration
class CiMACD: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
FastEmaPeriod
Returns the averaging period for the fast EMA.
Returned value
Returns the averaging period for the fast EMA, defined at the indicator creation.
SlowEmaPeriod
Returns the averaging period for the slow EMA.
Returned value
Returns the averaging period for the slow EMA, defined at the indicator creation.
SignalPeriod
Returns the averaging period for the signal line.
Returned value
Returns the averaging period for the signal line, defined at the indicator creation.
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int fast_ema_period, // Fast EMA period
int slow_ema_period, // Slow EMA period
int signal_period, // Signal period
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
fast_ema_period
[in] Fast EMA period.
slow_ema_period
[in] Slow EMA period.
signal_period
[in] Signal line period.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiMomentum
CiMomentum is a class intended for using the Momentum technical indicator.
Description
The CiMomentum class provides the creation, setup and access to the data of the Momentum
indicator.
Declaration
class CiMomentum: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiOsMA
CiOsMA is a class intended for using the Moving Average of Oscillator (MACD histogram) technical
indicator.
Description
The CiOsMA class provides the creation, setup and access to the data of the Moving Average of
Oscillator (MACD histogram) indicator.
Declaration
class CiOsMA: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
FastEmaPeriod
Returns the averaging period for the fast EMA.
Returned value
Returns the averaging period for the fast EMA, defined at the indicator creation.
SlowEmaPeriod
Returns the averaging period for the slow EMA.
Returned value
Returns the averaging period for the slow EMA, defined at the indicator creation.
SignalPeriod
Returns the averaging period for the signal line.
Returned value
Returns the averaging period for the signal line, defined at the indicator creation.
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int fast_ema_period, // Fast EMA period
int slow_ema_period, // Slow EMA period
int signal_period, // Signal line period
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
fast_ema_period
[in] Fast EMA period.
slow_ema_period
[in] Slow EMA period.
signal_period
[in] Signal line period.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiRSI
CiRSI is a class intended for using the Relative Strength Index technical indicator.
Description
The CiRSI class provides the creation, setup and access to the data of the Relative Strength Index
indicator.
Declaration
class CiRSI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int applied // Price type or handle to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiRVI
CiRVI is a class intended for using the Relative Vigor Index technical indicator.
Description
The CiRVI class provides the creation, setup and access to the data of the Relative Vigor Index
indicator.
Declaration
class CiRVI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiStochastic
CiStochastic is a class intended for using the Stochastic Oscillator technical indicator.
Description
The CiStochastic class provides the creation, setup and access to the data of the Stochastic Oscillator
indicator.
Declaration
class CiStochastic: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
Kperiod
Returns the averaging period for the %K line.
Returned value
Returns the averaging period for the %K line, defined at the indicator creation.
Dperiod
Returns the averaging period for the %D line.
Returned value
Returns the averaging period for the %D line, defined at the indicator creation.
Slowing
Returns the period of slowing.
Returned value
MaMethod
Returns the averaging method.
Returned value
PriceField
Returns the price type (Low/High or Close/Close) to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int Kperiod, // Averaging period of %K
int Dperiod, // Averaging period of %D
int slowing, // Slowing period
ENUM_MA_METHOD ma_method, // Averaging method
ENUM_STO_PRICE price_field // Price type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Kperiod
[in] Averaging period of %K line.
Dperiod
[in] Averaging period of %D line.
slowing
[in] Slowing period.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
price_field
[in] Price type (Low/High or Close/Close) to apply (ENUM_STO_PRICE enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiTriX
CiTriX is a class intended for using the Triple Exponential Moving Averages Oscillator technical
indicator.
Description
The CiTriX class provides the creation, setup and access to the data of the Triple Exponential Moving
Averages Oscillator indicator.
Declaration
class CiTriX: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int applied // Price type or handle
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type of handle to apply.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiWPR
CiWPR is a class intended for using the Williams' Percent Range technical indicator.
Description
The CiWPR class provides the creation, setup and access to the data of the Williams' Percent Range
indicator.
Declaration
class CiWPR: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes
Create Methods
Input/output
CalcPeriod
Returns the period for calculation.
Returned value
Returns the the period for calculation, defined at the indicator creation.
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int calc_period // Calculation period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
calc_period
[in] Period for calculation.
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
Volume Indicators
This group of chapters contains technical details of Volume Indicator classes of the MQL5 Standard
Library and descriptions of all its key components.
Class/group Description
CiAD Accumulation/Distribution
CiVolumes Volumes
CiAD
CiAD is a class intended for using the Accumulation/Distribution technical indicator.
Description
The CiAD class provides the creation, setup and access to the data of the Accumulation/Distribution
indicator.
Declaration
class CiAD: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes
Create Methods
Input/output
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiMFI
CiMFI is a class intended for using the Money Flow Index technical indicator.
Description
The CiMFI class provides the creation, setup and access to the data of the Money Flow Index indicator.
Declaration
class CiMFI: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes
Create Methods
Input/output
MaPeriod
Returns the averaging period.
Returned value
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiOBV
CiOBV is a class intended for using the On Balance Volume technical indicator.
Description
The CiOBV class provides the creation, setup and access to the data of the On Balance Volume
indicator.
Declaration
class CiOBV: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes
Create Methods
Input/output
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiVolumes
CiVolumes is a class intended for using the Volumes technical indicator.
Description
The CiVolumes class provides the creation, setup and access to the data of the Volumes indicator.
Declaration
class CiVolumes: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes
Create Methods
Input/output
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
Class/group Description
CiAlligator Alligator
CiFractals Fractals
CiAC
CiAC is a class intended for using the Accelerator Oscillator technical indicator.
Description
The CiAC class provides the creation, setup and access to the data of the Accelerator Oscillator
indicator.
Declaration
class CiAC: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods
Input/output
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period // Period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiAlligator
CiAlligator is a class intended for using the Alligator technical indicator.
Description
The CiAlligator class provides the creation, setup and access to the data of the Alligator indicator.
Declaration
class CiAlligator: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes
Create Methods
Input/output
JawPeriod
Returns the averaging period for the Jaw line.
Returned value
Returns the averaging period for the Jaw line, defined at the indicator creation.
JawShift
Returns the horizontal shift of the Jaws line.
Returned value
TeethPeriod
Returns the averaging period for the Teeth line.
Returned value
Returns the averaging period for the Teeth line, defined at the indicator creation.
TeethShift
Returns the horizontal shift of the Teeths line.
Returned value
LipsPeriod
Returns the averaging period for the Lips line.
Returned value
Returns the averaging period for the Lips line, defined at the indicator creation.
LipsShift
Returns the horizontal shift of the Lips line.
Returned value
MaMethod
Returns the averaging method.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int jaw_period, // Jaws period
int jaw_shift, // Jaws shift
int teeth_period, // Teeths period
int teeth_shift, // Teeths shift
int lips_period, // Lips period
int lips_shift, // Lips shift
ENUM_MA_METHOD ma_method, // Averaging method
int applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
jaw_period
[in] Jaws period.
jaw_shift
[in] Jaws shift.
teeth_period
[in] Teeths period.
teeth_shift
[in] Teeths shift.
lips_period
[in] Lips period.
lips_shift
[in] Lips shift.
ma_method
[in] Moving average method (ENUM_MA_METHOD enumeration).
applied
[in] Volume type to apply.
Returned value
Jaw
Returns the buffer element of the Jaws line by the specified index.
double Jaw(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the Jaws line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Teeth
Returns the buffer element of the Teeths line by the specified index.
double Teeth(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the Teeths line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Lips
Returns the buffer element of the Lips line by the specified index.
double Lips(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the Lips line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
Type
Returns the object type identifier.
Returned value
CiAO
CiAO is a class intended for using the Awesome Oscillator technical indicator.
Description
The CiAO class provides the creation, setup and access to the data of the Awesome Oscillator
indicator.
Declaration
class CiAO: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods
Input/output
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period // Period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiFractals
CiFractals is a class intended for using the Fractals technical indicator.
Description
The CiFractals class provides the creation, setup and access to the data of the Fractals indicator.
Declaration
class CiFractals: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods
Input/output
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period // Period
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Returned value
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Lower
Returns the buffer element of the lower buffer by the specified index.
double Lower(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiGator
CiGator is a class intended for using the Gator Oscillator technical indicator.
Description
The CiGator class provides the creation, setup and access to the data of the Gator Oscillator
indicator.
Declaration
class CiGator: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes
Create Methods
Input/output
JawPeriod
Returns the averaging period for the Jaws line.
Returned value
Returns the averaging period for the Jaws line, defined at the indicator creation.
JawShift
Returns the horizontal shift of the Jaws line.
Returned value
TeethPeriod
Returns the averaging period for the Teeth line.
Returned value
Returns the averaging period for the Teeth line, defined at the indicator creation.
TeethShift
Returns the horizontal shift of the Teeths line.
Returned value
LipsPeriod
Returns the averaging period for the Lips line.
Returned value
Returns the averaging period for the Lips line, defined at the indicator creation.
LipsShift
Returns the horizontal shift of the Lips line.
Returned value
MaMethod
Returns the averaging method.
Returned value
Applied
Returns the price type or handle to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
int jaw_period, // Jaws period
int jaw_shift, // Jaws shift
int teeth_period, // Teeths period
int teeth_shift, // Teeths shift
int lips_period, // Lips period
int lips_shift, // Lips shift
ENUM_MA_METHOD ma_method, // Averaging method
int applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
jaw_period
[in] Jaws period.
jaw_shift
[in] Jaws shift.
teeth_period
[in] Teeths period.
teeth_shift
[in] Teeths shift.
lips_period
[in] Lips period.
lips_shift
[in] Lips shift.
ma_method
[in] Averaging method (ENUM_MA_METHOD enumeration).
applied
[in] Volume type to apply.
Returned value
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Lower
Returns the buffer element of the lower buffer by the specified index.
double Upper(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
Type
Returns the object type identifier.
Returned value
CiBWMFI
CiBWMFI is a class intended for using the Market Facilitation Index by Bill Williams technical indicator.
Description
The CiBWMFI class provides the creation, setup and access to the data of the Market Facilitation
Index by Bill Williams indicator.
Declaration
class CiBWMFI: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes
Create Methods
Input/output
Applied
Returns the volume type to apply.
Returned value
Create
It creates the indicator with specified parameters.
bool Create(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied // Volume type to apply
)
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Returned value
Main
Returns the buffer element by the specified index.
double Main(
int index // Index
)
Parameters
index
[in] Element index.
Returned value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
Type
Returns the object type identifier.
Returned value
CiCustom
CiCustom is a class intended for using the custom technical indicators.
Description
The CiCustom class provides the creation, setup and access to the data of the custom indicator.
Declaration
class CiCustom: public CIndicator
Title
#include <Indicators\Custom.mqh>
Class Methods
Attributes
Input/output
NumBuffers
Sets the number of buffers.
bool NumBuffers(
int buffers // number of buffers
)
Returned value
NumParams
Gets the number of parameters.
Returned value
ParamType
Gets a type of the parameter with specified index.
ENUM_DATATYPE ParamType(
int index // parameter index
) const
Parameters
index
[in] Parameter index.
Returned value
Returns the data type (value of ENUM_DATATYPE enumeration) of the parameter with specified
index, used in indicator creation.
Note
ParamLong
Gets the value of specified parameter of long type.
long ParamLong(
int index // index
) const
Parameters
index
[in] Parameter index.
Returned value
The value of specified parameter of long type, used in creation of the indicator.
Note
ParamDouble
Gets the value of specified parameter of double type.
double ParamDouble(
int index // index
) const
Parameters
index
[in] Parameter index.
Returned value
The value of specified parameter of double type, used in creation of the indicator.
Note
ParamString
Gets the value of specified parameter of string type.
string ParamString(
int index // index
) const
Parameters
index
[in] Parameter index.
Returned value
Note
Type
Returns the object type identifier.
Returned value
Trade Classes
This section contains technical details of working with trade classes and description of the relevant
components of the MQL5 standard library.
Using trade classes will save time when creating custom programs (experts).
MQL5 Standard Library (in terms of data sets) is placed in the terminal working directory, in the
Include\Arrays folder.
Class/Group Description
CAccountInfo
CAccountInfo is a class for easy access to the currently opened trade account properties.
Description
CAccountInfo class provides easy access to the currently opened trade account properties.
Declaration
class CAccountInfo : public CObject
Title
#include <Trade\AccountInfo.mqh>
Additional methods
Login
Gets the account number.
Returned value
Account number.
TradeMode
Gets the trade mode.
Returned value
TradeModeDescription
Gets the trade mode as a string.
Returned value
Leverage
Gets the amount of given leverage.
Returned value
MarginMode
Gets the mode of account Stop Out.
Returned value
MarginModeDescription
Gets the mode of setting minimal margin level as a string.
Returned value
TradeAllowed
Gets the flag of trade allowance.
Returned value
TradeExpert
Gets the flag of automated trade allowance.
Returned value
LimitOrders
Gets the maximal number of allowed pending orders
Returned value
Note
0 - no limits.
Balance
Gets the balance of account.
Returned value
Credit
Gets the amount of given credit.
Returned value
Profit
Gets the amount of current profit on account.
Returned value
Equity
Gets the amount of current equity on account.
Returned value
Margin
Gets the amount of reserved margin.
Returned value
FreeMargin
Gets the amount of free margin.
Returned value
MarginLevel
Gets the level of margin.
Returned value
Level of margin.
MarginCall
Gets the level of margin for a deposit.
Returned value
MarginStopOut
Gets the level of margin for Stop Out.
Returned value
Name
Gets the client name.
Returned value
Client name.
Server
Gets the trade server name.
Returned value
Currency
Gets the deposit currency name.
Returned value
Company
Gets the company name, that serves an account.
Returned value
InfoInteger
Gets the value of specified integer type property.
long InfoInteger(
ENUM_ACCOUNT_INFO_INTEGER prop_id // property ID
) const
Parameters
prop_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_INTEGER enumeration.
Returned value
InfoDouble
Gets the value of specified double type property.
double InfoDouble(
ENUM_ACCOUNT_INFO_DOUBLE prop_id // property ID
) const
Parameters
prop_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_DOUBLE enumeration.
Returned value
InfoString
Gets the value of specified string type property.
string InfoString(
ENUM_ACCOUNT_INFO_STRING prop_id // property ID
) const
Parameters
prop_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_STRING enumeration.
Returned value
OrderProfitCheck
The function calculates the profit for the current account, based on the parameters passed. The
function is used for pre-evaluation of the result of a trade operation. The value is returned in the
account currency.
double OrderProfitCheck(
const string symbol, // symbol
ENUM_ORDER_TYPE trade_operation, // operation type (ORDER_TYPE_BUY or ORDER_TYPE_SELL)
double volume, // volume
double price_open, // open price
double price_close // close price
) const
Parameters
symbol
[in] Symbol for trade operation.
trade_operation
[in] Type of trade operation (ENUM_ORDER_TYPE enumeration).
volume
[in] Volume of trade operation.
price_open
[in] Open price.
price_close
[in] Close price.
Returned value
MarginCheck
Gets the amount of margin, required for trade operation.
double MarginCheck(
const string symbol, // symbol
ENUM_ORDER_TYPE trade_operation, // operation
double volume, // volume
double price // price
) const
Parameters
symbol
[in] Symbol for trade operation.
trade_operation
[in] Type of trade operation (ENUM_ORDER_TYPE enumeration).
volume
[in] Volume of trade operation.
price
[in] Price of trade operation.
Returned value
FreeMarginCheck
Gets the amount of free margin, left after trade operation.
double FreeMarginCheck(
const string symbol, // symbol
ENUM_ORDER_TYPE trade_operation, // operation
double volume, // volume
double price // price
) const
Parameters
symbol
[in] Symbol for trade operation.
trade_operation
[in] Type of trade operation (ENUM_ORDER_TYPE enumeration).
volume
[in] Volume of trade operation.
price
[in] Price of trade operation.
Returned value
MaxLotCheck
Gets the maximal possible volume of trade operation.
double MaxLotCheck(
const string symbol, // symbol
ENUM_ORDER_TYPE trade_operation, // operation
double price // price
) const
Parameters
symbol
[in] Symbol for trade operation.
trade_operation
[in] Type of trade operation (ENUM_ORDER_TYPE enumeration).
price
[in] Price of trade operation.
Returned value
CSymbolInfo
CSymbolInfo is a class for easy access to the symbol properties.
Description
Declaration
class CSymbolInfo : public CObject
Title
#include <Trade\SymbolInfo.mqh>
Controlling
Properties
Volumes
Miscellaneous
Levels
(in points)
Bid prices
Ask prices
Prices
Trade modes
Swaps
Quantization
Contracts sizes
Swaps sizes
Text properties
Service functions
Refresh
Refreshes the symbol data.
void Refresh()
Returned value
None.
Note
RefreshRates
Refreshes the symbol quotes data.
bool RefreshRates()
Returned value
Note
Name
Gets symbol name.
Returned value
Symbol name.
Name
Sets symbol name.
Returned value
None.
Select
Gets the "Market Watch" symbol flag.
Returned value
Select
Sets the "Market Watch" symbol flag.
bool Select()
Returned value
IsSynchronized
Checks the symbol synchronization with server.
Returned value
Note
Volume
Gets the volume of last deal.
Returned value
Note
VolumeHigh
Gets the maximal volume of the day.
Returned value
Note
VolumeLow
Gets the minimal volume of the day.
Returned value
Note
VolumeBid
Gets the volume of the current Bid.
Returned value
Note
VolumeAsk
Gets the volume of the current Ask.
Returned value
Note
Time
Gets the time of last quote.
Returned value
Note
Spread
Gets the amount of spread (in points).
Returned value
Note
SpreadFloat
Gets the flag of floating spread.
Returned value
Note
TickBookDepth
Gets the depth of ticks saving.
Returned value
Note
StopsLevel
Gets the minimal stop level for orders (in points).
Returned value
Note
FreezeLevel
Gets the freeze level (in points).
Returned value
Note
Bid
Gets the current Bid price.
Returned value
Note
BidHigh
Gets the maximal Bid price of the day.
Returned value
Note
BidLow
Gets the minimal Bid price of the day.
Returned value
Note
Ask
Gets the current Ask price.
Returned value
Note
AskHigh
Gets the maximal Ask price for a day.
Returned value
Note
AskLow
Gets the minimal Ask price for a day.
Returned value
Note
Last
Gets the current Last price.
Returned value
LastHigh
Gets the maximal Last price of the day.
Returned value
Note
LastLow
Gets the minimal Last price of the day.
Returned value
Note
TradeCalcMode
Gets the mode of contract cost calculation.
Returned value
Note
TradeCalcModeDescription
Gets the mode of contract cost calculation as a string.
Returned value
Note
TradeMode
Gets the order execution type.
Returned value
Note
TradeModeDescription
Gets the trade mode as a string.
Returned value
Note
TradeExecution
Gets the trade execution mode.
Returned value
Note
TradeExecutionDescription
Gets the description of trade execution mode as a string.
Returned value
Note
SwapMode
Gets the swap calculation mode.
Returned value
Note
SwapModeDescription
Gets the swap mode description as a string.
Returned value
Note
SwapRollover3days
Gets the swap rollover day.
Returned value
Note
SwapRollover3daysDescription
Gets the swap rollover day as a string.
Returned value
Note
MarginInitial
Gets the value of initial margin.
double MarginInitial()
Returned value
Note
It points the amount of margin (in margin currency of instrument), that is charged from one lot.
Used to check client's equity, when he enters the market.
MarginMaintenance
Gets the value of maintenance margin.
double MarginMaintenance()
Returned value
Note
It points the amount of margin (in margin currency of instrument), that is charged from one lot.
Used to check client's equity, when the account state is changed. If the maintenance margin is equal
to 0, then the initial margin is used.
MarginLong
Gets the rate of margin charging on long positons.
Returned value
Note
MarginShort
Gets the rate of margin charging on short positons.
Returned value
Note
MarginLimit
Gets the rate of margin charging on Limit orders.
Returned value
Note
MarginStop
Gets the rate of margin charging on Stop orders.
Returned value
Note
MarginStopLimit
Gets the rate of margin charging on Stop Limit orders.
Returned value
Note
TradeTimeFlags
Gets the flags of the order expiration allowed modes.
Returned value
Note
TradeFillFlags
Gets the flags of the order filling allowed modes.
Returned value
Note
Digits
Gets the number of digits after period.
Returned value
Note
Point
Gets the value of one point.
Returned value
Note
TickValue
Gets the cost of tick (minimal change of price).
Returned value
Note
TickValueProfit
Gets the calculated tick price for a profitable position.
Returned value
Note
TickValueLoss
Gets the calculated tick price for a losing position.
Returned value
Note
TickSize
Gets the minimal change of price.
Returned value
Note
ContractSize
Gets the amount of trade contract.
Returned value
Note
LotsMin
Gets the minimal volume to close a deal.
Returned value
Note
LotsMax
Gets the maximal volume to close a deal.
Returned value
Note
LotsStep
Gets the minimal step of volume change to close a deal.
Returned value
Note
LotsLimit
Gets the maximal allowed volume of opened position and pending orders (direction insensitive) for
one symbol.
Returned value
The maximal allowed volume of opened position and pending orders (direction insensitive) for one
symbol.
Note
SwapLong
Gets the value of long position swap.
Returned value
Note
SwapShort
Gets the value of short position swap.
Returned value
Note
CurrencyBase
Gets the name of symbol base currency.
Returned value
Note
CurrencyProfit
Gets the profit currency name.
Returned value
Note
CurrencyMargin
Gets the margin currency name.
Returned value
Note
Bank
Gets the name of current quote source.
Returned value
Note
Description
Gets the string description of symbol.
Returned value
Note
Path
Gets the path in symbols tree.
Returned value
Note
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_SYMBOL_INFO_INTEGER prop_id, // property ID
long& var // reference to variable
) const
Parameters
prop_id
[in] ID of integer type property (value of ENUM_SYMBOL_INFO_INTEGER enumeration).
var
[out] Reference to long type variable to place result.
Returned value
Note
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_SYMBOL_INFO_DOUBLE prop_id, // property ID
double& var // reference to variable
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_SYMBOL_INFO_DOUBLE enumeration).
var
[out] Reference to double type variable to place result.
Returned value
Note
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_SYMBOL_INFO_STRING prop_id, // property ID
string& var // reference to variable
) const
Parameters
prop_id
[in] ID of text property.
var
[out] Reference to string type variable to place result.
Returned value
Note
NormalizePrice
Returns the value of price, normalized using the symbol properties.
double NormalizePrice(
double price // price
) const
Parameters
price
[in] Price.
Returned value
Normalized price.
Note
COrderInfo
COrderInfo is a class for easy access to the pending order properties.
Description
Declaration
class COrderInfo : public CObject
Title
#include <Trade\OrderInfo.mqh>
State
Selection
Ticket
Gets the ticket of an order, previously selected for access using the Select method.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TimeSetup
Gets the time of order placement.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
OrderType
Gets the order type.
ENUM_ORDER_TYPE OrderType()
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeDescription
Gets the order type as a string.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
State
Gets the order state.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
StateDescription
Gets the order state as a string.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TimeExpiration
Gets the order expiration time.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TimeDone
Gets the time of order execution or cancellation.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeFilling
Gets the order filling type.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeFillingDescription
Gets the order filling type as a string.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeTime
Gets the type of order at the time of the expiration.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeTimeDescription
Gets the order type by expiration time as a string.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Magic
Gets the ID of expert, that placed the order.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PositionId
Gets the ID of position.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
VolumeInitial
Gets the initial volume of order.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
VolumeCurrent
Gets the unfilled volume of order.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PriceOpen
Gets the order price.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
StopLoss
Gets the order's Stop Loss.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TakeProfit
Gets the order's Take Profit.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PriceCurrent
Gets the current price by order symbol.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PriceStopLimit
Gets the price of setting limit order.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Symbol
Gets the name of order symbol.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Comment
Gets the order comment.
Returned value
Order comment.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_ORDER_PROPERTY_INTEGER prop_id, // property ID
long& var // reference to variable
) const
Parameters
prop_id
[in] ID of integer type property (value of ENUM_ORDER_PROPERTY_INTEGER enumeration).
var
[out] Reference to long type variable to place result.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_ORDER_PROPERTY_DOUBLE prop_id, // property ID
double& var // reference to variable
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_ORDER_PROPERTY_DOUBLE enumeration).
var
[out] Reference to double type variable to place result.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_ORDER_PROPERTY_STRING prop_id, // property ID
string& var // reference to variable
) const
Parameters
prop_id
[in] ID of text property.
var
[out] Reference to string type variable to place result.
Returned value
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
StoreState
Saves the order parameters.
void StoreState()
Returned value
None.
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Returned value
true - if the order parameters have changed since the last call of the StoreState() method,
otherwise - false.
Select
Selects an order by ticket for further access to its properties.
bool Select(
ulong ticket // order ticket
)
Returned value
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex(
int index // order index
)
Returned value
CHistoryOrderInfo
CHistoryOrderInfo is a class for easy access to the history order properties.
Description
Declaration
class CHistoryOrderInfo : public CObject
Title
#include <Trade\HistoryOrderInfo.mqh>
Selection
TimeSetup
Gets the time of order placement.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
OrderType
Gets the order type.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TypeDescription
Gets the order type as a string.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
State
Gets the order state.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
StateDescription
Gets the order state as a string.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TimeExpiration
Gets the time of order expiration.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TimeDone
Gets the time of order execution or cancellation.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TypeFilling
Gets the type of order execution by remainder.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TypeFillingDescription
Gets the type of order execution by remainder as a string.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TypeTime
Gets the type of order at the time of the expiration.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TypeTimeDescription
Gets the order type by expiration time as a string.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
Magic
Gets the ID of the Expert Advisor, that placed the order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
PositionId
Gets the ID of position.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
VolumeInitial
Gets the initial volume of order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
VolumeCurrent
Gets the unfilled volume of order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
PriceOpen
Gets the order price.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
StopLoss
Gets the Stop Loss price of the order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
TakeProfit
Gets the the Take Profit price of the order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
PriceCurrent
Gets the current price of the order's symbol.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
PriceStopLimit
Gets the stop limit price of the order.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
Symbol
Gets the name of order symbol.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
Comment
Gets the order comment.
Returned value
Order comment.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_ORDER_PROPERTY_INTEGER prop_id, // property ID
long& var // reference to variable
) const
Parameters
prop_id
[in] ID of integer type property (value of ENUM_ORDER_PROPERTY_INTEGER enumeration).
var
[out] Reference to long type variable to place result.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_ORDER_PROPERTY_DOUBLE prop_id, // property ID
double& var // reference to variable
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_ORDER_PROPERTY_DOUBLE enumeration).
var
[out] Reference to double type variable to place result.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_ORDER_PROPERTY_STRING prop_id, // property ID
string& var // reference to variable
) const
Parameters
prop_id
[in] ID of text property (value of ENUM_ORDER_PROPERTY_STRING enumeration).
var
[out] Reference to string type variable to place result.
Returned value
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
Returned value
Order ticket.
void Ticket(
ulong ticket // order ticket
)
Parameters
ticket
[in] Order ticket.
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex(
int index // order index
)
Returned value
CPositionInfo
CPositionInfo is a class for easy access to the open position properties.
Description
Declaration
class CPositionInfo : public CObject
Title
#include <Trade\PositionInfo.mqh>
Selection
State
Time
Gets the time of position opening.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PositionType
Gets the position type.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TypeDescription
Gets the position type as a string.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Magic
Gets the ID of Expert Advisor, opened the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Identifier
Gets the ID of position.
Returned value
ID of position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Volume
Gets the volume of position.
Returned value
Volume of position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PriceOpen
Gets the price of position opening.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
StopLoss
Gets the Stop Loss price of the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
TakeProfit
Gets the Take Profit price of the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
PriceCurrent
Gets the current price by position symbol.
Returned value
Commission
Gets the amount of commission of the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Swap
Gets the amount of swap of the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Profit
Gets the amount of current profit of the position.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Symbol
Gets the name of position symbol.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_POSITION_PROPERTY_INTEGER prop_id, // property ID
long& var // reference to variable
) const
Parameters
prop_id
[in] ID of integer type property (value of ENUM_POSITION_PROPERTY_INTEGER enumeration).
var
[out] Reference to long type variable to place result.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_POSITION_PROPERTY_DOUBLE prop_id, // property ID
double& var // reference to variable
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_POSITION_PROPERTY_DOUBLE enumeration).
var
[in] Reference to double type variable to place result.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_POSITION_PROPERTY_STRING prop_id, // property ID
string& var // reference to variable
) const
Parameters
prop_id
[in] ID of text property (value of ENUM_POSITION_PROPERTY_STRING enumeration).
var
[out] Reference to string type variable to place result.
Returned value
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
Select
Select the position for further work.
bool Select(
const string symbol // symbol
)
Parameters
symbol
[in] Symbol for position selection.
SelectByIndex
Selects the position by index for further access to its properties.
bool SelectByIndex(
int index // position index
)
Returned value
StoreState
Saves the position parameters.
void StoreState()
Returned value
None.
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Returned value
true - if the position parameters have changed since the last call of the StoreState() method,
otherwise - false.
CDealInfo
CDealInfo is a class for easy access to the deal properties.
Description
Declaration
class CDealInfo : public CObject
Title
#include <Trade\DealInfo.mqh>
property
Selection
Order
Gets the order by which the deal is executed.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Time
Gets the time of deal execution.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
DealType
Gets the deal type.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
TypeDescription
Gets the deal type as a string.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Entry
Gets the deal direction.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
EntryDescription
Gets the deal direction as a string.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Magic
Gets the ID of the Expert Advisor, that executed the deal.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
PositionId
Gets the ID of position, in which the deal was involved.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Volume
Gets the volume of deal.
Returned value
Volume of deal.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Price
Gets the deal price.
Returned value
Deal price.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Commission
Gets the amount of commission of the deal.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Swap
Gets the amount of swap when position is closed.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Profit
Gets the financial result of the deal.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Symbol
Gets the name of the deal symbol.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Comment
Gets the deal comment.
Returned value
Deal comment.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_DEAL_PROPERTY_INTEGER prop_id, // property ID
long& var // reference to variable
) const
Parameters
prop_id
[in] ID of integer type property (value of ENUM_DEAL_PROPERTY_INTEGER enumeration).
var
[out] Reference to long type variable to place result.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_DEAL_PROPERTY_DOUBLE prop_id, // property ID
double& var // reference to variable
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_DEAL_PROPERTY_DOUBLE enumeration).
var
[in] Reference to double type variable to place result.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_DEAL_PROPERTY_STRING prop_id, // property ID
string& var // reference to variable
) const
Parameters
prop_id
[in] ID of text property (value of ENUM_DEAL_PROPERTY_STRING enumeration).
var
[out] Reference to string type variable to place result.
Returned value
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
Returned value
Deal ticket.
void Ticket(
ulong ticket // ticket
)
Parameters
ticket
[in] Deal ticket.
SelectByIndex
Selects the deal by index for further access to its properties.
bool SelectByIndex(
int index // order index
)
Returned value
CTrade
CTrade is a class for easy access to the trade functions.
Description
Declaration
class CTrade : public CObject
Title
#include <Trade\Trade.mqh>
Setting parameters
Additional methods
RequestVolume Gets the trade volume (in lots), used in the last
request
request
Auxiliary methods
LogLevel
Sets logging level for messages.
void LogLevel(
int log_level // logging level
)
Parameters
log_level
[in] Logging level.
Returned value
None.
Note
SetExpertMagicNumber
Sets the expert ID.
void SetExpertMagicNumber(
ulong magic // ID
)
Parameters
magic
[in] New ID of the expert.
Returned value
None.
SetDeviationInPoints
Sets the allowed deviation.
void SetDeviationInPoints(
ulong deviation // deviation
)
Parameters
deviation
[in] Allowed deviation.
Returned value
None.
SetTypeFilling
Sets filling type of the order.
void SetTypeFilling(
ENUM_ORDER_TYPE_FILLING filling // order filling type
)
Parameters
filling
[in] Order filling type (value of ENUM_ORDER_TYPE_FILLING enumeration).
Returned value
None.
OrderOpen
Places the pending order with set parameters.
bool OrderOpen(
const string symbol, // symbol
ENUM_ORDER_TYPE order_type, // order type
double volume, // order volume
double limit_price, // StopLimit price
double price, // execution price
double sl, // Stop Loss price
double tp, // Take Profit price
ENUM_ORDER_TYPE_TIME type_time, // type by expiration
datetime expiration, // expiration
const string comment="" // comment
)
Parameters
symbol
[in] Name of trade instrument.
order_type
[in] Type of order trade operation (value of ENUM_ORDER_TYPE enumeration).
volume
[in] Requested order volume.
limit_price
[in] Price at which the StopLimit order will be placed.
price
[in] Price at which the order must be executed.
sl
[in] Price at which the Stop Loss will trigger.
tp
[in] Price at which the Take Profit will trigger.
type_time
[in] Order type by execution (value of ENUM_ORDER_TYPE_TIME enumeration).
expiration
[in] Expiration date of pending order.
comment=""
[in] Order comment.
Returned value
Note
Successful completion of the OrderSend(...) method does not always mean successful execution of
the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode() and value, returned by ResultOrder().
OrderModify
Modifies the pending order parameters.
bool OrderModify(
ulong ticket, // order ticket
double price, // execution price
double sl, // Stop Loss price
double tp, // Take Profit price
ENUM_ORDER_TYPE_TIME type_time, // type by expiration
datetime expiration // expiration
)
Parameters
ticket
[in] Order ticket.
price
[in] The new price by which the order must be executed (or the previous value, if the change is
not necessary).
sl
[in] The new price by which the Stop Loss will trigger (or the previous value, if the change is not
necessary).
tp
[in] The new price by which the Take Profit will trigger (or the previous value, if the change is not
necessary).
type_time
[in] The new type of order by expiration (or the previous value, if the change is not necessary),
value of ENUM_ORDER_TYPE_TIME enumeration.
expiration
[in] The new expiration date of pending order (or the previous value, if the change is not
necessary).
Returned value
Note
Successful completion of the OrderModify(...) method does not always mean successful execution of
the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode().
OrderDelete
Deletes the pending order.
bool OrderDelete(
ulong ticket // order ticket
)
Parameters
ticket
[in] Order ticket.
Returned value
Note
Successful completion of the OrderDelete(...) method does not always mean successful execution of
the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode().
PositionOpen
Opens the position with set parameters.
bool PositionOpen(
const string symbol, // symbol
ENUM_ORDER_TYPE order_type, // position type
double volume, // position volume
double price, // execution price
double sl, // Stop Loss price
double tp, // Take Profit price
const string comment="" // comment
)
Parameters
symbol
[in] Name of trade instrument, by which it is intended to open position.
order_type
[in] Type of position trade operation (value of ENUM_ORDER_TYPE enumeration).
volume
[in] Requested position volume.
price
[in] Price at which the position must be opened.
sl
[in] Price at which the Stop Loss will trigger.
tp
[in] Price at which the Take Profit will trigger.
comment=""
[in] Position comment.
Returned value
Note
Successful completion of the PositionOpen(...) method does not always mean successful execution
of the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode() and value, returned by ResultDeal().
PositionModify
Modifies the position parameters by specified symbol.
bool PositionModify(
const string symbol, // symbol
double sl, // Stop Loss price
double tp // Take Profit price
)
Parameters
symbol
[in] Name of trade instrument, by which it is intended to modify position.
sl
[in] The new price by which the Stop Loss will trigger (or the previous value, if the change is not
necessary).
tp
[in] The new price by which the Take Profit will trigger (or the previous value, if the change is not
necessary).
Returned value
Note
Successful completion of the PositionModify(...) method does not always mean successful execution
of the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode().
PositionClose
Closes the position by specified symbol.
bool PositionClose(
const string symbol, // symbol
ulong deviation=ULONG_MAX // deviation
)
Parameters
symbol
[in] Name of trade instrument, by which it is intended to close position.
deviation=ULONG_MAX
[in] Maximal deviation from the current price (in points).
Returned value
Note
Successful completion of the PositionClose(...) method does not always mean successful execution
of the trade operation. It's necessary to check the result of trade request (trade server return code)
using ResultRetcode().
Buy
Opens a long position with specified parameters.
bool Buy(
double volume, // position volume
const string symbol=NULL, // symbol
double price=0.0, // price
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
const string comment="" // comment
)
Parameters
volume
[in] Position volume.
symbol=NULL
[in] Position symbol. If the symbol isn't specified, the current symbol will be used.
price=0.0
[in] Price. If the price isn't specified, the current market Ask price will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
comment=""
[in] Comment.
Returned value
Note
Successful completion of the Buy(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
Sell
Opens a short position with specified parameters.
bool Sell(
double volume, // position volume
const string symbol=NULL, // symbol
double price=0.0, // price
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
const string comment="" // comment
)
Parameters
volume
[in] Position volume.
symbol=NULL
[in] Position symbol. If the symbol isn't specified, the current symbol will be used.
price=0.0
[in] Price. If the price isn't specified, the current market Bid price will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
comment=""
[in] Comment.
Returned value
Note
Successful completion of the Sell(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
BuyLimit
Places the pending order of Buy Limit type (buy at the price, lower than current market price) with
specified parameters.
bool BuyLimit(
double volume, // order volume
double price, // order price
const string symbol=NULL, // symbol
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC, // order lifetime
datetime expiration=0, // order expiration time
const string comment="" // comment
)
Parameters
volume
[in] Order volume.
price
[in] Order price.
symbol=NULL
[in] Order symbol. If the symbol isn't specified, the current symbol will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
type_time=ORDER_TIME_GTC
[in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration).
expiration=0
[in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED).
comment=""
[in] Order comment.
Returned value
Note
Successful completion of the BuyLimit(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
BuyStop
Places the pending order of Buy Stop type (buy at the price, higher than current market price) with
specified parameters.
bool BuyStop(
double volume, // order volume
double price, // order price
const string symbol=NULL, // symbol
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC, // order lifetime
datetime expiration=0, // order expiration time
const string comment="" // comment
)
Parameters
volume
[in] Order volume.
price
[in] Order price.
symbol=NULL
[in] Order symbol. If the symbol isn't specified, the current symbol will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
type_time=ORDER_TIME_GTC
[in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration).
expiration=0
[in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED).
comment=""
[in] Order comment.
Returned value
Note
Successful completion of the BuyStop(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
SellLimit
Places the pending order of Sell Limit type (sell at the price, higher than current market price) with
specified parameters.
bool SellLimit(
double volume, // order volume
double price, // order price
const string symbol=NULL, // symbol
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC, // order lifetime
datetime expiration=0, // order expiration time
const string comment="" // comment
)
Parameters
volume
[in] Order volume.
price
[in] Order price.
symbol=NULL
[in] Order symbol. If the symbol isn't specified, the current symbol will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
type_time=ORDER_TIME_GTC
[in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration).
expiration=0
[in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED).
comment=""
[in] Order comment.
Returned value
Note
Successful completion of the SellLimit(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
SellStop
Places the pending order of Buy Stop type (sell at the price, lower than current market price) with
specified parameters.
bool SellStop(
double volume, // order volume
double price, // order price
const string symbol=NULL, // symbol
double sl=0.0, // stop loss price
double tp=0.0, // take profit price
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC, // order lifetime
datetime expiration=0, // order expiration time
const string comment="" // comment
)
Parameters
volume
[in] Order volume.
price
[in] Order price.
symbol=NULL
[in] Order symbol. If the symbol isn't specified, the current symbol will be used.
sl=0.0
[in] Stop Loss price.
tp=0.0
[in] Take Profit price.
type_time=ORDER_TIME_GTC
[in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration).
expiration=0
[in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED).
comment=""
[in] Order comment.
Returned value
Note
Successful completion of the SellStop(...) method does not always mean successful execution of the
trade operation. It's necessary to check the result of trade request (trade server return code) using
ResultRetcode() and value, returned by ResultDeal().
Request
Gets the copy of the last request structure.
void Request(
MqlTradeRequest& request // target structure
) const
Parameters
request
[out] Reference to the structure of MqlTradeRequest type.
Returned value
None.
RequestAction
Gets the trade operation type.
Returned value
RequestActionDescription
Gets the trade operation type as string.
Returned value
RequestMagic
Gets the magic number of the Expert Advisor.
Returned value
The magic number (ID) of the Expert Advisor, used in the last request.
RequestOrder
Gets the order ticket, used in the last request.
Returned value
RequestSymbol
Gets the name of the symbol, used in the last request.
Returned value
RequestVolume
Gets the trade volume (in lots), used in the last request.
Returned value
RequestPrice
Gets the price, used in the last request.
Returned value
RequestStopLimit
Gets the price of pending order of Stop Limit type, used in the last request.
Returned value
The price of pending order of Stop Limit type, used in the last request.
RequestSL
Gets the Stop Loss price of the order, used in the last request.
Returned value
RequestTP
Gets the Take Profit price of the order, used in the last request.
Returned value
RequestDeviation
Gets the price deviation of the order, used in the last request.
Returned value
RequestType
Gets the type of the order, used in the last request.
Returned value
RequestTypeDescription
Gets the type of the order (as string) , used in the last request.
Returned value
RequestTypeFilling
Gets the filling type of the order, used in the last request.
Returned value
The filling type of the order (value of ENUM_ORDER_TYPE_FILLING), used in the last request.
RequestTypeFillingDescription
Gets the filling type of the order (as string), used in the last request.
Returned value
The filling type (as string) of the order, used in the last request.
RequestTypeTime
Gets the validity period of the order, used in the last request.
Returned value
The validity period of the order (value of ENUM_ORDER_TYPE_TIME enumeration), used in the last
request.
RequestTypeTimeDescription
Gets the validity period of the order (as string), used in the last request.
Returned value
The validity period of the order (as string), used in the last request.
RequestExpiration
Gets the expiration time of the order, used in the last request.
Returned value
RequestComment
Gets the comment of the order, used in the last request.
Returned value
Result
Gets the copy of the structure of the last request result.
void Result(
MqlTradeResult& result // reference
) const
Parameters
result
[out] Reference to the structure of MqlTradeRequest type.
Returned value
None.
ResultRetcode
Gets the code of request result.
Returned value
ResultRetcodeDescription
Gets the code of request result as text.
Returned value
ResultDeal
Gets the deal ticket.
Returned value
ResultOrder
Gets the order ticket.
Returned value
ResultVolume
Gets the volume of deal or order.
Returned value
ResultPrice
Gets the price, confirmed by broker.
Returned value
ResultBid
Gets the current bid price (the requote).
Returned value
ResultAsk
Gets the current ask price (the requote).
Returned value
ResultComment
Gets the broker comment.
Returned value
CheckResult
Gets the copy of the structure of the last request check result.
void CheckResult(
MqlTradeCheckResult& check_result // reference
) const
Parameters
check_result
[out] Reference to the target structure of the MqlTradeCheckResult type.
Returned value
None.
CheckResultRetcode
Gets the value of the retcode field of MqlTradeCheckResult type, filled while checking of the request
correctness.
uint CheckResultRetcode() const
Returned value
The value of the retcode field (error code) of MqlTradeCheckResult type, filled while checking of the
request correctness.
CheckResultRetcodeDescription
Gets the string description of the retcode field of MqlTradeCheckResult type, filled while checking of
the request correctness.
string ResultRetcodeDescription() const
Returned value
The string description of the retcode field (Error code) of MqlTradeCheckResult type, filled while
checking of the request correctness.
CheckResultBalance
Gets the value of the balance field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultBalance() const
Returned value
The value of the balance field (balance value that will be after the execution of the trade operation)
of MqlTradeCheckResult type, filled while checking of the request correctness.
CheckResultEquity
Gets the value of the equity field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultEquity() const
Returned value
The value of the equity field (equity value that will be after the execution of the trade operation) of
MqlTradeCheckResult type, filled while checking of the request correctness.
CheckResultProfit
Gets the value of the profit field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultProfit() const
Returned value
The value of the profit field (profit value that will be after the execution of the trade operation) of
MqlTradeCheckResult type, filled while checking of the request correctness.
CheckResultMargin
Gets the value of the margin field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultMargin() const
Returned value
The value of the margin field (margin required for the trade operation) of MqlTradeCheckResult
type, filled while checking of the request correctness.
CheckResultMarginFree
Gets the value of the margin_free field of MqlTradeCheckResult type, filled while checking of the
request correctness.
Returned value
The value of the margin_free field (free margin that will be left after the execution of the trade
operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
CheckResultMarginLevel
Gets the value of the margin_level field of MqlTradeCheckResult type, filled while checking of the
request correctness.
Returned value
The value of the margin_level field (margin level that will be set after the execution of the trade
operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
CheckResultComment
The value of the comment field of MqlTradeCheckResult type, filled while checking of the request
correctness.
Returned value
The value of the comment field (Comment to the reply code, error description) of
MqlTradeCheckResult type, filled while checking of the request correctness.
PrintRequest
Prints the last request parameters into journal.
Returned value
None.
PrintResult
Prints the results of the last request into journal.
Returned value
None.
FormatRequest
Prepares the formatted string with last request parameters.
string FormatRequest(
string& str, // target string
const MqlTradeRequest& request // request
) const
Parameters
str
[in] Target string, passed by reference.
request
[in] A structure of MqlTradeRequest type with parameters of the last request.
Returned value
None.
FormatRequestResult
Prepares the formatted string with results of the last request execution.
string FormatRequestResult(
string& str, // string
const MqlTradeRequest& request, // request structure
const MqlTradeResult& result // result structure
) const
Parameters
str
[in] Target string, passed by reference.
request
[in] A structure of MqlTradeRequest type with parameters of the last request.
result
[in] A structure of MqlTradeResult type with results of the last request.
Returned value
None.
The use of these classes will save time when creating the trading strategies.
MQL5 Standard Library (in terms of trading strategies) is placed in the terminal directory, in the
Include\Expert folder.
The use of these classes will save time when creating the trading strategies.
MQL5 Standard Library (in terms of trading strategies) is placed in the terminal directory, in the
Include\Expert folder.
Class Description
CExpert
CExpert is a base class for trading strategies. It has built-in algorithms for working with time series
and indicators and a set of virtual methods for trading strategy.
Description
The CExpert class is a set of virtual methods for implementation of trading strategies.
Declaration
class CExpert : public CObject
Title
#include <Expert\CExpert.mqh>
Class Methods
Public methods:
Initialization/Deinitialization
Protected methods:
Initialization/Deinitialization
Update Methods
Processing Methods
virtual CloseAll Closes the opened position and delete all orders
Trailing Methods
Event flags
Service methods
Init
Class instance initialization method.
bool Init(
string symbol, // Symbol
ENUM_TIMEFRAMES period, // Period
bool every_tick, // Flag
long magic==0 // Magic number
)
Parameters
symbol
[in] Symbol.
period
[in] Period (ENUM_TIMEFRAMES enumeration).
every_tick
[in] Flag.
magic==0
[in] Expert Advisor ID (Magic number).
Returned value
InitSignal
Initializes Trading Signal object.
Parameters
signal==NULL
[in] Pointer to the CExpertSignal class object (or its heir).
Returned value
Note
InitTrailing
Initializes Trailing Stop object.
Parameters
trailing==NULL
[in] Pointer to the CExpertTrailing class object (or its heir).
Returned value
Note
InitMoney
Initializes the Money Management object.
Parameters
money==NULL
[in] Pointer to the CExpertMoney class object (or its heir).
Returned value
Note
Deinit
Class instance deinitialization method.
Returned value
None.
int MaxOrders()
Returned value
void MaxOrders(
int max_orders // max orders
)
Parameters
max_orders
[in] New value of maximal allowed number of orders.
Note
OnTick
The OnTick event handler.
Returned value
None.
Note
OnTrade
The OnTrade event handler.
Returned value
None.
Note
OnTimer
The OnTimer event handler.
Returned value
None.
InitParameters
Initializes parameters.
Returned value
Note
The InitParameters() function of CExpert base class does nothing and always returns true.
InitIndicators
Initializes all indicators and time series.
Returned value
Note
It calls consequentially InitIndicators() virtual methods of trading signal, trailing stop and money
management objects.
InitTrade
Initializes Trade object.
Parameters
magic
[in] Magic number of Expert Advisor, it will be used in trade operations.
Returned value
DeinitTrade
Deinitializes Trade object.
Returned value
None.
DeinitSignal
Deinitializes Expert Signal object.
Returned value
None.
DeinitTrailing
Deinitializes Trailing Stop object.
Returned value
None.
DeinitMoney
Deinitializes Money Management object.
Returned value
None.
DeinitIndicators
Deinitializes all indicators and time series.
Returned value
None.
Refresh
Updates all data.
Returned value
Note
It allows to determine the need of tick processing. If it needed, it updates all quotes and time series
and indicators data and returns true.
Processing
Main processing algorithm.
Returned value
Note
1. Checks the presence of the opened position on the symbol. If there isn't opened position, skip
steps №2, №3 and №4.
2. Checks conditions to reverse opened position (calls CheckReverse method). If position has been
"reversed", exit.
3. Checks conditions to close position (calls CheckClose method). If position has been closed, skip
step №4.
4. Checks conditions to modify position parameters (calls CheckTrailingStop method). If position
parameters has been modified, exit.
5. Check the presence of pending orders on the symbol. If there isn't any pending orders, go to step
№9.
6. Checks condition to delete order (calls CheckDeleteOrderLong for buy pending orders or
CheckDeleteOrderShort for sell pending orders). If the order has been deleted, go to step №9.
7. Check conditions to modify pending order parameters (calls CheckTrailingOrderLong for buy
orders or CheckTrailingOrderShort for sell orders). If the order parameters has been modified, exit.
8. Exit.
9. Checks conditions to open position (calls CheckOpen method).
Implementation
//+------------------------------------------------------------------+
//| Main function |
//| INPUT: no. |
//| OUTPUT: true-if any trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::Processing()
{
//--- check if open positions
if(m_position.Select(m_symbol.Name()))
{
//--- open position is available
//--- check the possibility of closing the position/delete pending orders
if(!CheckClose())
{
//--- check the possibility of modifying the position
if(CheckTrailingStop()) return(true);
}
}
//--- check the possibility of opening a position/setting pending order
if(CheckOpen()) return(true);
//--- check if plased pending orders
int total=OrdersTotal();
if(total!=0)
{
for(int i=total-1;i>=0;i--)
{
m_order.Select(OrderGetTicket(i));
if(m_order.Symbol()!=m_symbol.Name()) continue;
if(m_order.Type()==ORDER_TYPE_BUY_LIMIT || m_order.Type()==ORDER_TYPE_BUY_STOP)
{
//--- check the ability to delete a pending order to buy
if(CheckDeleteOrderLong()) return(true);
//--- check the possibility of modifying a pending order to buy
if(CheckTrailingOrderLong()) return(true);
}
else
{
//--- check the ability to delete a pending order to sell
if(CheckDeleteOrderShort()) return(true);
//--- check the possibility of modifying a pending order to sell
if(CheckTrailingOrderShort()) return(true);
}
}
}
//--- return without operations
return(false);
}
CheckOpen
Checks conditions to open position.
Returned value
Note
Implementation
//+------------------------------------------------------------------+
//| Check for position open or limit/stop order set |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckOpen()
{
if(CheckOpenLong()) return(true);
if(CheckOpenShort()) return(true);
//--- return without operations
return(false);
}
CheckOpenLong
Checks conditions to open long position.
Returned value
Note
It checks conditions to open long position (by calling CheckOpenLong method of Expert Signal
object) and opens the long position (by calling OpenLong method) if necessary.
Implementation
//+------------------------------------------------------------------+
//| Check for long position open or limit/stop order set |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckOpenLong()
{
double price,sl,tp;
datetime expiration=TimeCurrent();
//--- check signal for long enter operations
if(m_signal.CheckOpenLong(price,sl,tp,expiration))
{
if(!m_trade.SetOrderExpiration(expiration))
{
m_expiration=expiration;
}
return(OpenLong(price,sl,tp));
}
//--- return without operations
return(false);
}
CheckOpenShort
Checks conditions to open short position.
Returned value
Note
It checks conditions to open short position (by calling CheckOpenShort method of Expert Signal
object) and opens the short position (by calling OpenShort method) if necessary.
Implementation
//+------------------------------------------------------------------+
//| Check for short position open or limit/stop order set |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckOpenShort()
{
double price,sl,tp;
datetime expiration=TimeCurrent();
//--- check signal for short enter operations
if(m_signal.CheckOpenShort(price,sl,tp,expiration))
{
if(!m_trade.SetOrderExpiration(expiration))
{
m_expiration=expiration;
}
return(OpenShort(price,sl,tp));
}
//--- return without operations
return(false);
}
OpenLong
Opens the long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets trading volume (by calling LotOpenLong method) and opens the long position (by calling Buy
method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+
//| Long position open or limit/stop order set |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::OpenLong(double price,double sl,double tp)
{
//--- get lot for open
double lot=LotOpenLong(price,sl);
//--- check lot for open
if(lot==0.0) return(false);
//---
return(m_trade.Buy(lot,price,sl,tp));
}
OpenShort
Opens the short position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets trading volume (by calling LotOpenShort method) and opens the short position (by calling Sell
method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+
//| Short position open or limit/stop order set |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::OpenShort(double price,double sl,double tp)
{
//--- get lot for open
double lot=LotOpenShort(price,sl);
//--- check lot for open
if(lot==0.0) return(false);
//---
return(m_trade.Sell(lot,price,sl,tp));
}
CheckClose
Checks conditions to close position.
Returned value
Note
1. It checks Expert Advisor Stop Out conditions (by calling CheckClose method of money
management object). If condition is satisfied, it closes the position and deletes all orders (by calling
CloseAll) and exit.
2. It checks conditions to close long or short position (by calling CheckCloseLong or CheckCloseShort
methods) and if position is closed, it deletes all orders (by calling DeleteOrders method).
Implementation
//+------------------------------------------------------------------+
//| Check for position close or limit/stop order delete |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckClose()
{
double lot;
//--- position must be selected before call
if((lot=m_money.CheckClose(GetPointer(m_position)))!=0.0)
return(CloseAll(lot));
//--- check for position type
if(m_position.Type()==POSITION_TYPE_BUY)
{
//--- check the possibility of closing the long position / delete pending orders to buy
if(CheckCloseLong())
{
DeleteOrders();
return(true);
}
}
else
{
//--- check the possibility of closing the short position / delete pending orders to sell
if(CheckCloseShort())
{
DeleteOrders();
return(true);
}
}
//--- return without operations
return(false);
}
CheckCloseLong
Checks conditions to close long position.
Returned value
Note
It checks conditions to close long position (by calling CheckCloseLong method of Expert Signal
object) and if it satisfied, it closes the opened position (by calling CloseLong method).
Implementation
//+------------------------------------------------------------------+
//| Check for long position close or limit/stop order delete |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckCloseLong()
{
double price;
//--- check for long close operations
if(m_signal.CheckCloseLong(price))
return(CloseLong(price));
//--- return without operations
return(false);
}
CheckCloseShort
Checks conditions to close short position.
Returned value
Note
It checks conditions to close short position (by calling CheckCloseShort method of Expert Signal
object) and if it satisfied, it closes the position (by calling CloseShort method).
Implementation
//+------------------------------------------------------------------+
//| Check for short position close or limit/stop order delete |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckCloseShort()
{
double price;
//--- check for short close operations
if(m_signal.CheckCloseShort(price))
return(CloseShort(price));
//--- return without operations
return(false);
}
CloseAll
It performs partial of full position closing.
Parameters
lot
[in] Number of lots to reduce the position.
Returned value
Note
It performs partial of full position closing (by calling the Sell and Buy methods of CTrade class object
for the long/short positions) and deletes all orders (by calling the DeleteOrders method).
Implementation
//+------------------------------------------------------------------+
//| Position close and orders delete |
//| INPUT: lot. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CloseAll(double lot)
{
bool result;
//--- check for close operations
if(m_position.Type()==POSITION_TYPE_BUY) result=m_trade.Sell(lot,0,0,0);
else result=m_trade.Buy(lot,0,0,0);
result|=DeleteOrders();
//---
return(result);
}
Close
Closes the opened position.
Returned value
Note
Closes the position (by calling PositionClose method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Position close |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::Close()
{
return(m_trade.PositionClose(m_symbol.Name()));
}
CloseLong
Closes the long position.
Parameters
price
[in] Closing price.
Returned value
Note
Closes the long position (by calling Sell method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Long position close |
//| INPUT: price. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CloseLong(double price)
{
return(m_trade.Sell(m_position.Volume(),price,0,0));
}
CloseShort
Closes the short position.
Parameters
price
[in] Closing price.
Returned value
Note
Closes the short position (by calling Buy method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Short position close |
//| INPUT: price. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CloseShort(double price)
{
return(m_trade.Buy(m_position.Volume(),price,0,0));
}
CheckReverse
Checks conditions to reverse opened position.
Returned value
Note
Implementation
//+------------------------------------------------------------------+
//| Check for position reverse |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckReverse()
{
if(m_position.Type()==POSITION_TYPE_BUY)
{
//--- check the possibility of reverse the long position
if(CheckReverseLong()) return(true);
}
else
//--- check the possibility of reverse the short position
if(CheckReverseShort()) return(true);
//--- return without operations
return(false);
}
CheckReverseLong
Checks conditions to reverse long position.
Returned value
Note
It checks conditions to reverse long position (by calling CheckReverseLong method of Expert Signal
object) and perform reverse operation of the current long position (by calling ReverseLong method)
if necessary.
Implementation
//+------------------------------------------------------------------+
//| Check for long position reverse |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckReverseLong()
{
double price,sl,tp;
datetime expiration=TimeCurrent();
//--- check signal for long reverse operations
if(m_signal.CheckReverseLong(price,sl,tp,expiration)) return(ReverseLong(price,sl,tp));
//--- return without operations
return(false);
}
CheckReverseShort
Checks conditions to reverse short position.
Returned value
Note
It checks conditions to reverse short position (by calling CheckReverseShort method of Expert Signal
object) and perform reverse operation of the current short position (by calling ReverseShort
method) if necessary.
Implementation
//+------------------------------------------------------------------+
//| Check for short position reverse |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckReverseShort()
{
double price,sl,tp;
datetime expiration=TimeCurrent();
//--- check signal for short reverse operations
if(m_signal.CheckReverseShort(price,sl,tp,expiration)) return(ReverseShort(price,sl,tp));
//--- return without operations
return(false);
}
ReverseLong
Perform reverse operation of long position.
Parameters
price
[in] Price of long position reverse.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets position reverse volume (by calling LotReverse method) and perform trade operation of long
position reverse (by calling Sell method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+
//| Long position reverse |
//| INPUT: price - price, |
//| sl - stop loss, |
//| tp - take profit. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::ReverseLong(double price,double sl,double tp)
{
//--- get lot for reverse
double lot=LotReverse(sl);
//--- check lot
if(lot==0.0) return(false);
//---
return(m_trade.Sell(lot,price,sl,tp));
}
ReverseShort
Perform reverse operation of short position.
Parameters
price
[in] Price of short position reverse.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets position reverse volume (by calling LotReverse method) and perform trade operation of
short position reverse (by calling Buy method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+
//| Short position reverse |
//| INPUT: price - price, |
//| sl - stop loss, |
//| tp - take profit. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::ReverseShort(double price,double sl,double tp)
{
//--- get lot for reverse
double lot=LotReverse(sl);
//--- check lot
if(lot==0.0) return(false);
//---
return(m_trade.Buy(lot,price,sl,tp));
}
CheckTrailingStop
It checks Trailing Stop conditions of the opened position.
Returned value
Note
It checks Trailing Stop conditions of the opened position (by calling CheckTrailingStopLong or
CheckTrailingStopShort for long and short positions).
Implementation
//+------------------------------------------------------------------+
//| Check for trailing stop/profit position |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckTrailingStop()
{
//--- position must be selected before call
if(m_position.Type()==POSITION_TYPE_BUY)
{
//--- check the possibility of modifying the long position
if(CheckTrailingStopLong()) return(true);
}
else
{
//--- check the possibility of modifying the short position
if(CheckTrailingStopShort()) return(true);
}
//--- return without operations
return(false);
}
CheckTrailingStopLong
It checks Trailing Stop conditions of the opened long position.
Returned value
Note
It checks Trailing Stop conditions of the opened long position (by calling CheckTrailingStopLong
method of Expert Trailing object). If conditions are satisfied, it modifies the position parameters
(by calling TrailingStopLong method).
Implementation
//+------------------------------------------------------------------+
//| Check for trailing stop/profit long position |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckTrailingStopLong()
{
double sl=EMPTY_VALUE;
double tp=EMPTY_VALUE;
//--- check for long trailing stop operations
if(m_trailing.CheckTrailingStopLong(GetPointer(m_position),sl,tp))
{
if(sl==EMPTY_VALUE) sl=m_position.StopLoss();
if(tp==EMPTY_VALUE) tp=m_position.TakeProfit();
//--- long trailing stop operations
return(TrailingStopLong(sl,tp));
}
//--- return without operations
return(false);
}
CheckTrailingStopShort
It checks Trailing Stop conditions of the opened short position.
Returned value
Note
It checks Trailing Stop conditions of the opened short position (by calling CheckTrailingStopShort
method of Expert Trailing object). If conditions are satisfied, it modifies the position parameters
(by calling TrailingStopShort method).
Implementation
//+------------------------------------------------------------------+
//| Check for trailing stop/profit short position |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckTrailingStopShort()
{
double sl=EMPTY_VALUE;
double tp=EMPTY_VALUE;
//--- check for short trailing stop operations
if(m_trailing.CheckTrailingStopShort(GetPointer(m_position),sl,tp))
{
if(sl==EMPTY_VALUE) sl=m_position.StopLoss();
if(tp==EMPTY_VALUE) tp=m_position.TakeProfit();
//--- short trailing stop operations
return(TrailingStopShort(sl,tp));
}
//--- return without operations
return(false);
}
TrailingStopLong
The function modifies parameters of the opened long position.
Parameters
sl
[in] New Stop Loss price.
tp
[in] New Take Profit price.
Returned value
Note
The function modifies parameters of the opened long position (by calling PositionModify method of
CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Trailing stop/profit long position |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::TrailingStopLong(double sl,double tp)
{
return(m_trade.PositionModify(m_symbol.Name(),sl,tp));
}
TrailingStopShort
The function modifies parameters of the opened short position.
Parameters
sl
[in] New Stop Loss price.
tp
[in] New Take Profit price.
Returned value
Note
The function modifies parameters of the opened short position (by calling PositionModify method of
CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Trailing stop/profit short position |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::TrailingStopShort(double sl,double tp)
{
return(m_trade.PositionModify(m_symbol.Name(),sl,tp));
}
CheckTrailingOrderLong
It checks Trailing Stop conditions of buy limit/stop pending order.
Returned value
Note
It checks Trailing Stop conditions for buy limit/stop pending order (by calling
CheckTrailingOrderLong method of Trade Signals object) and modifies the order parameters if
necessary (by calling TrailingOrderLong method).
Implementation
//+------------------------------------------------------------------+
//| Check for trailing long limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckTrailingOrderLong()
{
double price;
//--- check the possibility of modifying the long order
if(m_signal.CheckTrailingOrderLong(GetPointer(m_order),price))
return(TrailingOrderLong(price));
//--- return without operations
return(false);
}
CheckTrailingOrderShort
It checks Trailing Stop conditions of sell limit/stop pending order.
Returned value
Note
It checks Trailing Stop conditions for sell limit/stop pending order (by calling
CheckTrailingOrderShort method of Trade Signals object) and modifies the order parameters if
necessary (by calling TrailingOrderShort method).
Implementation
//+------------------------------------------------------------------+
//| Check for trailing short limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckTrailingOrderShort()
{
double price;
//--- check the possibility of modifying the short order
if(m_signal.CheckTrailingOrderShort(GetPointer(m_order),price))
return(TrailingOrderShort(price));
//--- return without operations
return(false);
}
TrailingOrderLong
The function modifies parameters of buy limit/stop pending order.
Parameters
delta
[in] Price delta.
Returned value
Note
It modifies parameters of buy limit/stop order (by calling OrderModify method of CTrade class
object).
Implementation
//+------------------------------------------------------------------+
//| Trailing long limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::TrailingOrderLong(double delta)
{
ulong ticket=m_order.Ticket();
double price =m_order.PriceOpen()-delta;
double sl =m_order.StopLoss()-delta;
double tp =m_order.TakeProfit()-delta;
//--- modifying the long order
return(m_trade.OrderModify(ticket,price,sl,tp,m_order.TypeTime(),m_order.TimeExpiration()));
}
TrailingOrderShort
The function modifies parameters of sell limit/stop pending order.
Parameters
delta
[in] Price delta.
Returned value
Note
It modifies parameters of sell limit/stop order (by calling OrderModify method of CTrade class
object).
Implementation
//+------------------------------------------------------------------+
//| Trailing short limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::TrailingOrderShort(double delta)
{
ulong ticket=m_order.Ticket();
double price =m_order.PriceOpen()-delta;
double sl =m_order.StopLoss()-delta;
double tp =m_order.TakeProfit()-delta;
//--- modifying the short order
return(m_trade.OrderModify(ticket,price,sl,tp,m_order.TypeTime(),m_order.TimeExpiration()));
}
CheckDeleteOrderLong
It checks conditions to delete the buy limit/stop pending order.
Returned value
Note
Implementation
//+------------------------------------------------------------------+
//| Check for delete long limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckDeleteOrderLong()
{
double price;
//--- check the possibility of deleting the long order
if(m_expiration!=0 && TimeCurrent()>m_expiration)
{
m_expiration=0;
return(DeleteOrderLong());
}
if(m_signal.CheckCloseLong(price))
return(DeleteOrderLong());
//--- return without operations
return(false);
}
CheckDeleteOrderShort
It checks conditions to delete the sell limit/stop pending order.
Returned value
Note
Implementation
//+------------------------------------------------------------------+
//| Check for delete short limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation processed, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::CheckDeleteOrderShort()
{
double price;
//--- check the possibility of deleting the short order
if(m_expiration!=0 && TimeCurrent()>m_expiration)
{
m_expiration=0;
return(DeleteOrderShort());
}
if(m_signal.CheckCloseShort(price))
return(DeleteOrderShort());
//--- return without operations
return(false);
}
DeleteOrders
Deletes all orders.
Returned value
Note
Implementation
//+------------------------------------------------------------------+
//| Delete all limit/stop orders |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::DeleteOrders()
{
bool result=false;
int total=OrdersTotal();
//---
for(int i=total-1;i>=0;i--)
{
if(m_order.Select(OrderGetTicket(i)))
{
if(m_order.Symbol()!=m_symbol.Name()) continue;
result|=DeleteOrder();
}
}
//---
return(result);
}
DeleteOrder
Deletes the limit/stop pending order.
Returned value
Note
It deletes the limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Delete limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::DeleteOrder()
{
return(m_trade.OrderDelete(m_order.Ticket()));
}
DeleteOrderLong
Deletes the buy limit/stop pending order.
Returned value
Note
It deletes the buy limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Delete long limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::DeleteOrderLong()
{
return(m_trade.OrderDelete(m_order.Ticket()));
}
DeleteOrderShort
Deletes the sell limit/stop pending order.
Returned value
Note
It deletes the sell limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Delete short limit/stop order |
//| INPUT: no. |
//| OUTPUT: true-if trade operation successful, false otherwise. |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool CExpert::DeleteOrderShort()
{
return(m_trade.OrderDelete(m_order.Ticket()));
}
LotOpenLong
Gets trade volume for buy operation.
double LotOpenLong(
double price, // Price
double sl // Stop Loss
)
Parameters
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets trade volume for buy operation (by calling CheckOpenLong method of money management
object).
Implementation
//+------------------------------------------------------------------+
//| Method of getting the lot for open long position. |
//| INPUT: no. |
//| OUTPUT: lot for open. |
//| REMARK: no. |
//+------------------------------------------------------------------+
double CExpert::LotOpenLong(double price,double sl)
{
double lot=m_money.CheckOpenLong(price,sl);
//---
return(lot);
}
LotOpenShort
Gets trade volume for sell operation.
double LotOpenShort(
double price, // Price
double sl // Stop Loss
)
Parameters
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Returned value
Note
It gets trade volume for sell operation (by calling CheckOpenLong method of money management
object).
Implementation
//+------------------------------------------------------------------+
//| Method of getting the lot for open short position. |
//| INPUT: no. |
//| OUTPUT: lot for open. |
//| REMARK: no. |
//+------------------------------------------------------------------+
double CExpert::LotOpenShort(double price,double sl)
{
double lot=m_money.CheckOpenShort(price,sl);
//---
return(lot);
}
LotReverse
Gets trade volume for position reverse.
double LotReverse(
double sl // Stop Loss
)
Parameters
sl
[in] Stop Loss price.
Returned value
Note
It gets trade volume for position reverse operation (by calling CheckReverse method of money
management object).
Implementation
//+------------------------------------------------------------------+
//| Method of getting the lot for reverse position. |
//| INPUT: sl - stop loss. |
//| OUTPUT: lot for open. |
//| REMARK: no. |
//+------------------------------------------------------------------+
double CExpert::LotReverse(double sl)
{
return(m_money.CheckReverse(GetPointer(m_position),sl));
}
PrepareHistoryDate
Sets starting date for the trade history.
void PrepareHistoryDate()
Note
The trade history tracking period is set from the beginning of the month (but not less than one
day).
HistoryPoint
Creates checkpoint of trade history (saves number of positions, orders, deals and historical orders).
void HistoryPoint(
bool from_check_trade==false // flag
)
Parameters
from_check_trade==false
[in] flag to avoid the recursion.
Note
CheckTradeState
Compares the current state with the saved one and calls the corresponding event handler.
bool CheckTradeState()
Returned value
Note
It checks the number of positions, orders, deals and historical orders by comparing with the values,
saved by HistoryPoint method. If trade history has changed, it calls the corresponding virtual event
handler.
WaitEvent
Sets event waiting flag.
void WaitEvent(
ENUM_TRADE_EVENTS event // Flag
)
Parameters
event
[in] Event to track.
NoWaitEvent
Resets event waiting flag.
void NoWaitEvent(
ENUM_TRADE_EVENTS event // Flag
)
Parameters
event
[in] Event to reset.
IsWaitingPositionOpened
Returns true if Expert Advisor should handle the "Position Opened" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventPositionOpened() method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingPositionVolumeChanged
Returns true if Expert Advisor should handle the "Position volume changed" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventPositionVolumeChanged method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingPositionModified
Returns true if Expert Advisor should handle the "Position modified" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventPositionModified method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingPositionClosed
Returns true if Expert Advisor should handle the "Position closed" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventPositionClosed method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingPositionStopTake
Returns true if Expert Advisor should handle the "Position Stop Loss/Take Profit triggered" event,
overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventPositionStopTake method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingOrderPlaced
Returns true if Expert Advisor should handle the "Pending order placed" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventOrderPlaced method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingOrderModified
Returns true if Expert Advisor should handle the "Pending order modified" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventOrderModified method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
TradeEventOrderDeleted
Returns true if Expert Advisor should handle the "Pending order deleted" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventOrderDeleted method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
IsWaitingOrderTriggered
Returns true if Expert Advisor should handle the "Pending order triggered" event, overwise false.
Returned value
true if corresponding flag is set and event should handled, overwise false. The event is processed by
TradeEventOrderTriggered method.
Note
The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
TradeEventPositionStopTake
"Position Stop Loss/Take Profit triggered" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventOrderTriggered
"Pending order triggered" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventPositionOpened
"Position opened" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventPositionVolumeChanged
"Position volume changed" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventPositionModified
"Position modified" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventPositionClosed
"Position closed" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventOrderPlaced
"Pending order placed" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventOrderModified
"Pending order modified" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventOrderDeleted
"Pending order deleted" event handler.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TradeEventNotIdentified
Event handler of the non-identified event.
Returned value
Note
The virtual method of CExpert class does nothing and always returns true.
TimeframeAdd
Add a timeframe for tracking.
void TimeframeAdd(
ENUM_TIMEFRAMES period // Timeframe
)
Parameters
period
[in] Timeframe to track.
TimeframesFlags
The function returns the flag indicating the timeframes with a new bar.
int TimeframesFlags(
MqlDateTime& time // Variable for time
)
Parameters
time
[in] Variable of MqlDateTime type for new time, passed by reference.
Returned value
CExpertSignal
CExpertSignal is a base class for trading signals, it does nothing (except CheckReverseLong and
CheckReverseShort methods) but provides the interfaces.
You can find an examples of trading signal classes in the Expert\Signal\ folder.
Description
Declaration
class CExpertSignal : public CObject
Title
#include <Expert\ExpertSignal.mqh>
Class Methods
Initialization
Init
Initializes class members.
Parameters
symbol
[in] Pointer to CSymbolInfo object (CExpert class member).
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
adjusted_point
[in] Point size.
Returned value
InitIndicators
Initializes indicators and time series.
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Returned value
Note
ValidationSettings
Checks the settings.
Returned value
Note
CheckOpenLong
Checks conditions to open long position.
Parameters
price
[in][out] Variable for price, passed by reference.
sl
[in][out] Variable for "Stop Loss" price, passed by reference.
tp
[in][out] Variable for "Take Profit" price, passed by reference.
expiration
[in][out] Variable for order expiration time (if necessary), passed by reference.
Returned value
Note
CheckCloseLong
Checks conditions to close long position.
Parameters
price
[in][out] Variable for price, passed by reference.
Returned value
Note
CheckOpenShort
Checks conditions to open short position.
Parameters
price
[in][out] Variable for opening price, passed by reference.
sl
[in][out] Variable for "Stop Loss" price, passed by reference.
tp
[in][out] Variable for "Take Profit" price, passed by reference.
expiration
[in][out] Variable for order expiration time (if necessary), passed by reference.
Returned value
Note
CheckCloseShort
Checks conditions to close short position.
Parameters
price
[in][out] Variable for position closing price, passed by reference.
Returned value
Note
CheckReverseLong
Checks conditions of long position reversal.
Parameters
price
[in][out] Variable for reversal price, passed by reference.
sl
[in][out] Variable for "Stop Loss" price, passed by reference.
tp
[in][out] Variable for "Take Profit" price, passed by reference.
expiration
[in][out] Variable for order expiration time (if necessary), passed by reference.
Returned value
Note
The CheckReverseLong() method of the base class returns true if both CheckCloseLong and
CheckOpenShort conditions are satisfied and closing and opening prices are equal.
CheckReverseShort
Checks conditions of short position reversal.
Parameters
price
[in][out] Variable for reversal price, passed by reference.
sl
[in][out] Variable for "Stop Loss" price, passed by reference.
tp
[in][out] Variable for "Take Profit" price, passed by reference.
expiration
[in][out] Variable for order expiration time (if necessary), passed by reference.
Returned value
Note
The CheckReverseShort() method of the base class returns true if both CheckCloseShort and
CheckOpenLong conditions are satisfied and closing and opening prices are equal.
CheckTrailingOrderLong
Checks conditions to modify buy pending order.
Parameters
order
[in] Pointer to COrderInfo object.
price
[in][out] Variable for new order price, passed by reference.
Returned value
Note
CheckTrailingOrderShort
Checks conditions to modify sell pending order.
Parameters
order
[in] Pointer to COrderInfo object.
price
[in][out] Variable for new order price, passed by reference.
Returned value
Note
CExpertTrailing
CExpertTrailing is a base class for trailing algorithms, it does nothing but provides the interfaces.
Description
Declaration
class CExpertTrailing : public CObject
Title
#include <Expert\ExpertTrailing.mqh>
Class Methods
Initialization
Init
Initializes class members.
Parameters
symbol
[in] Pointer to CSymbolInfo object (CExpert class member).
period
[in] Timeframe.
adjusted_point
[in] Point size.
Returned value
InitIndicators
Initializes indicators and time series.
Parameters
indicators
[in] A pointer to indicators and time series collection (CExpert class member).
Returned value
Note
ValidationSettings
Checks the settings.
Returned value
Note
CheckTrailingStopLong
Checks conditions to modify long position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price, passed by reference.
tp
[in][out] Variable for Take Profit price, passed by reference.
Returned value
Note
CheckTrailingStopShort
Checks conditions to modify short position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price, passed by reference.
tp
[in][out] Variable for Take Profit price, passed by reference.
Returned value
Note
CExpertMoney
CExpertMoney is a base class for money and risk management algorithms.
Description
CExpertMoney is a base class for implementation of money and risk management classes.
Declaration
class CExpertMoney : public CObject
Title
#include <Expert\ExpertMoney.mqh>
Class Methods
Initialization
Percent
Sets the value of "Risk percent" parameter.
void Percent(
double perсent // Risk percent
)
Parameters
perсent
[in] Risk percent.
Returned value
None.
Init
Initializes class members.
Parameters
symbol
[in] Pointer to CSymbolInfo object (CExpert class member).
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
adjusted_point
[in] Point size.
Returned value
InitIndicators
Initializes indicators and time series.
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Returned value
Note
ValidationSettings
Checks the settings.
Returned value
Note
CheckOpenLong
Gets the volume for long position.
Parameters
price
[in] Opening price of long position.
sl
[in] Stop Loss price of long position.
Returned value
CheckOpenShort
Gets the volume for short position.
Parameters
price
[in] Opening price of short position.
sl
[in] Stop Loss price of short position.
Returned value
CheckReverse
Gets the volume for reverse of the position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in] Stop Loss price.
Returned value
CheckClose
Checks conditions to close position.
Returned value
Each of the modules of signals has its set of market modules (certain combination of prices and
values of an indicator).
Each market model has a significance that may vary with the range of 1 to 100. The higher is the
significance, the stronger the model is.
Each of the models generates a forecast of direction of the price movement.
A forecast of a module is the result of search for embedded models, and it is outputted as a number
within the range of -100 to 100. The sign determines the direction of forecast movement (negative
sign means the price will fall, positive sign means the price will rise). The absolute value
Examples
Consider an Expert Advisor with the following threshold levels: ThresholdOpen=20 and
ThresholdClose=90. Two modules of signals participate in making decisions on trade operations: the
MA module with weight 0.4 and the Stochastic module with weight 0.8. Let's analyze two variants of
obtained trade signals:
Variant 1.
The price crossed the rising MA upwards. This case corresponds to one of the market models
implemented in the MA module. This model implies a rise of price. Its significance is equal to 100. At
the same time, the Stochastic oscillator turned down and formed a divergence with price. This case
corresponds to one of the models implemented in the Stochastic module. This model implies a fall of
price. The weight of this model is 80.
Let's calculate the result of final "voting". The rate obtained from the MA module is calculated as 0.4 *
100 = 40. The value from the Stochastic module is calculated as 0.8 * (-80) = -64. The final value value
is calculated as the arithmetical mean of these two rates: (40 - 64)/2 = -12. The result of voting is the
signal for selling with relative strength equal to 12. The threshold level that is equal to 20 is not
reached. Thus a trade operation is not performed.
Variant 2.
The price crossed the rising MA downwards. This case corresponds to one of the models implemented
in the MA module.This model implies a rise of price. Its significance is equal to 10. At the same time,
the Stochastic oscillator turned down and formed a divergence with price. This case corresponds to
one of the models implemented in the Stochastic module. This model implies a fall of price. The
weight of this model is 80.
Let's calculate the result of final "voting". The rate obtained from the MA module is calculated as 0.4 *
10 = 4. The value from the Stochastic module is calculated as 0.8 * (-80) = -64. The final value is
calculated as the arithmetical mean of these two rates: (4 - 64)/2 = -30. The result of voting is the
signal for selling with relative strength equal to 30. The threshold level that is equal to 20 is reached.
Thus the result is the signal for opening a short position.
a) Divergence of the price and the Stochastic oscillator (variants 1 and 2).
b) The price crossed the MA indicator upwards (variant 1).
c) The price crossed the MA indicator downwards (variants 2).
For buying The indicator value is above 0 and it rises at the analyzed and at the previous
bars.
The indicator value is below 0 and it rises at the analyzed and at the previous
bars.
For selling The indicator value is below 0 and it falls at the analyzed and at the previous
bars.
The indicator value is below 0 and it falls at the analyzed and at the previous
bars.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
For buying Saucer — value of the indicator at the analyzed bar rises, and it fell at the
previous bars; at that, both values are above 0.
Crossing the zero line — value of the indicator is above 0 at the analyzed bar,
and it is below 0 at the previous bar.
Divergence — the first analyzed valley of the indicator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
In addition, the indicator must not rise above the zero level.
For selling Saucer — value of the indicator at the analyzed bar falls, and it rose at the
previous bars; at that, both values are below 0.
Crossing the zero line — value of the indicator is below 0 at the analyzed bar,
and it is above 0 at the previous bar.
Divergence — the first analyzed peak of the indicator is lower than the previous
one, and the corresponding price peak is higher than the previous one. In
addition, the indicator must not falls below the zero level.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
For buying Reverse — the oscillator turned upwards and its value at the analyzed bar is
below 0.
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
In addition, the oscillator must not rise above the zero level.
objections
to buying
No No signals.
objections
to selling
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
For selling Reverse — the oscillator turned downwards and its value at the analyzed bar is
above 0.
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak. In
addition, the oscillator must not fall below the zero level.
No No signals.
objections
to buying
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
For buying Reverse behind the level of overselling — the oscillator turned upwards and its
value at the analyzed bar is behind the level of overselling (default value is -100).
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
Double divergence — the oscillator form three consequent valley, each of them
is shallower than the previous one; and the price formed three corresponding
valleys, and each of them is deeper than the previous one.
For selling Reverse behind the level of overbuying — the oscillator turned downwards and
its value at the analyzed bar is behind the level of overbuying (default value is
100).
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
For buying Reverse behind the level of overselling — the oscillator turned upwards and its
value at the analyzed bar is behind the level of overselling (default value is 0.3).
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
Double divergence — the oscillator form three consequent valley, each of them
is shallower than the previous one; and the price formed three corresponding
valleys, and each of them is deeper than the previous one.
For selling Reverse behind the level of overbuying — the oscillator turned downwards and
its value at the analyzed bar is behind the level of overbuying (default value is
0.7).
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
For buying The price is near the lower line of the indicator at the analyzed bar.
The price crossed the upper line of the indicator at the analyzed bar.
For selling The price is near the upper line of the indicator at the analyzed bar.
The price crossed the lower line of the indicator at the analyzed bar.
No No signals.
objections
to buying
No No signals.
objections
to selling
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
No objections to buying The current date and time meet the specified
parameters.
No objections to selling The current date and time meet the specified
parameters.
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
For buying Reverse — the oscillator turned upwards (the oscillator rises at the analyzed bar
and falls at the previous one).
Crossing of the main and signal line — the main line is above the signal line at
the analyzed bar and below the signal line at the previous one.
Crossing the zero level — the main line is above the zero level at the analyzed
bar and below the zero level at the previous one.
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
Double divergence — the oscillator form three consequent valley, each of them
is shallower than the previous one; and the price formed three corresponding
valleys, and each of them is deeper than the previous one.
For selling Reverse — the oscillator turned downwards (the oscillator falls at the analyzed
bar and rises at the previous one).
Crossing of the main and signal line — the main line is below the signal line at
the analyzed bar and above the signal line at the previous one.
Crossing the zero level — the main line is below the zero level at the analyzed
bar and above the zero level at the previous one.
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
For buying Reverse — the indicator is below the price at the analyzed bar and above the price
at the previous one.
For selling Reverse — the indicator is above the price at the analyzed bar and below the price
at the previous one.
to buying
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
For buying Reverse behind the level of overselling — the oscillator turned upwards and its
value at the analyzed bar is behind the level of overselling (default value is 30).
Failed swing — the oscillator rises higher than the previous peak at the analyzed
bar.
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
Double divergence — the oscillator form three consequent valley, each of them
is shallower than the previous one; and the price formed three corresponding
valleys, and each of them is deeper than the previous one.
For selling Reverse behind the level of overbuying — the oscillator turned downwards and
its value at the analyzed bar is behind the level of overbuying (default value is
70).
Failed swing — the oscillator falls deeper than the previous valley at the analyzed
bar.
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Head/Shoulders — the oscillator formed three consequent peaks, and the mid
one is higher than the others.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
For buying Crossing of the main and signal line — the main line is above the signal line at the
analyzed bar and below the signal line at the previous one.
For selling Crossing of the main and signal line — the main line is below the signal line at the
analyzed bar and above the signal line at the previous one.
to buying
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
For buying Reverse — the oscillator turned upwards (the oscillator rises at the analyzed bar
and falls at the previous one).
Crossing of the main and signal line — the main line is above the signal line at
the analyzed bar and below the signal line at the previous one.
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
Double divergence — the oscillator form three consequent valley, each of them
is shallower than the previous one; and the price formed three corresponding
valleys, and each of them is deeper than the previous one.
For selling Reverse — the oscillator turned downwards (the oscillator falls at the analyzed bar
and rises at the previous one).
Crossing of the main and signal line — the main line is below the signal line at
the analyzed bar and above the signal line at the previous one.
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
Parameter Description
For buying Reverse — the oscillator turned upwards (the oscillator rises at the analyzed bar
and falls at the previous one).
Crossing the zero level — the main line is above the zero level at the analyzed
bar and below the zero level at the previous one.
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
For selling Reverse — the oscillator turned downwards (the oscillator falls at the analyzed
bar and rises at the previous one).
Crossing the zero level — the main line is below the zero level at the analyzed
bar and above the zero level at the previous one.
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
Parameter Description
For buying Reverse behind the level of overselling — the oscillator turned upwards and its
value at the analyzed bar is behind the level of overselling (default value is -20).
Divergence — the first analyzed valley of the oscillator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
For selling Reverse behind the level of overbuying — the oscillator turned downwards and
its value at the analyzed bar is behind the level of overbuying (default value is -
80).
Divergence — the first analyzed peak of the oscillator is lower than the previous
one, and the corresponding price peak is higher than the previous peak.
Note
Depending on the mode of operation of an Expert Advisor ("Every tick" or "Open prices only") an
analyzed bar is either the current bar (with index 0), or the last formed bar (with index 1).
Remember that the oscillator Williams Percent Range has a reversed scale. Its maximum value is -
100, and minimum is 0.
Adjustable Parameters
This module has the following adjustable parameters:
Parameter Description
The use of these classes will save time when creating (and testing) of trading strategies.
MQL5 Standard Library (in terms of trading strategies) is placed in the terminal directory, in the
Include\Expert\Trailing folder.
Class Description
CTrailingFixedPips
CTrailingFixedPips is a class with implementation of Trailing Stop algorithm, based on fixed points
trailing.
If position has Stop Loss price, it checks the minimal allowed Stop Loss distance to the current price.
If its value is lower, that Stop Loss level, it suggests to set new Stop Loss price. For this case if
position has Take Profit price, it suggests to set new Take Profit price.
If Expert Advisor has been initialized with the flag every_tick=false, it will perform all operations
(trading, trailing, etc) only at the new bar. For this case Take profit level can be used. It will allow you
to close opened position at Take Profit price before the new bar will be completed.
Description
CTrailingFixedPips implements the Trailing Stop algorithm, based on positions trailing with the fixed
points.
Declaration
class CTrailingFixedPips: public CExpertTrailing
Title
#include <Expert\Trailing\CTrailingFixedPips.mqh>
Class Methods
Initialization
StopLevel
Sets the value Stop Loss level (in points).
void StopLevel(
int stop_level // Stop Loss level
)
Parameters
stop_loss
[in] The value of Stop Loss level (in conventional 2/4-digit points).
Note
ProfitLevel
Sets the value of Take Profit level (in points).
void ProfitLevel(
int profit_level // Take profit level
)
Parameters
profit_level
[in] The value of Take Profit level (in conventional 2/4-digit points).
Note
ValidationSettings
Checks the settings.
Returned value
Note
The function checks Take Profit and Stop Loss levels. The correct values are 0 and values, greater
than minimal stop for stop orders for the symbol.
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
If Stop Loss level is equal to 0, the Trailing Stop is not used. If position already has Stop Loss price,
its value is assumed as a base price, overwise the position open price is assumed as a base price.
If the current Bid price is higher than base price+stop loss level, it suggests to set new Stop Loss
price. In this case, If position already has Take Profit price, it suggests to set new Take Profit price
equal to Bid price+take proft level.
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
If Stop Loss level is equal to 0, the Trailing Stop is not used. If position already has Stop Loss price,
its value is assumed as a base price, overwise the position open price is assumed as a base price.
If the current Ask price is lower than base price-stop loss level, it suggests to set new Stop Loss
price. In this case, If position already has Take Profit price, it suggests to set new Take Profit price
equal to Ask price-take proft level.
CTrailingMA
CTrailingMA is a class with implementation of Trailing Stop algorithm, based on the values of moving
average indicator.
Description
CTrailingMA class implements Trailing Stop algorithm, based on the values of moving average
indicator of the previous (completed) bar.
Declaration
class CTrailingMA: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingMA.mqh>
Class Methods
Initialization
Period
Sets period of moving average.
void Period(
int period // Smoothing period
)
Parameters
period
[in] Period of moving average.
Shift
Sets shift of moving average.
void Shift(
int shift // Shift
)
Parameters
shift
[in] Shift of moving average.
Method
Sets smoothing method of moving average.
void Method(
ENUM_MA_METHOD method // Smoothing method
)
Parameters
method
[in] Smoothing method of moving average indicator.
Applied
Sets applied price of moving average.
void Applied(
ENUM_APPLIED_PRICE applied // Applied price
)
Parameters
applied
[in] Applied price of moving average.
InitIndicators
Initializes indicators and time series.
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Returned value
ValidationSettings
Checks the settings.
Returned value
Note
The function checks the period of moving average, the correct values are positive.
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
The first it calculates the maximal allowed Stop Loss price, closest to the current price and
calculates Stop Loss price using the values of moving average indicator of the previous (completed)
bar.
If position already has Stop Loss price, its value is assumed as a base price, overwise the base price
is the open price of the position.
If the calculated Stop Loss price is higher than base price and lower than maximal allowed Stop Loss
price, it suggests to set new Stop Loss price.
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
The first it calculates the minimal allowed Stop Loss price, closest to the current price and
calculates Stop Loss price using the values of moving average indicator of the previous (completed)
bar.
If position already has Stop Loss price, its value is assumed as a base price, overwise the base price
is the open price of the position.
If the calculated Stop Loss price is higher than base price and lower than minimal allowed Stop Loss
price, it suggests to set new Stop Loss price.
CTrailingNone
CTrailingNone is a gag class. This class should be used at initialization of Trailng object if your
strategy doesn't use Trailing Stop.
Description
CTrailingNone class doesn't implement any Trailing Stop algorithms. The methods of checking Trailing
Stop conditions always return false.
Declaration
class CTrailingNone: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingNone.mqh>
Class Methods
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
CTrailingPSAR
CTrailingPSAR is a class with implementation of Trailing Stop algorithm, based on the values of of
Parabolic SAR indicator.
Description
CTrailingPSAR class implements the Trailing Stop algorithm, based on the values of Parabolic SAR
indicator of the previous (completed) bar.
Declaration
class CTrailingPSAR: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
Class Methods
Initialization
Step
Sets the value of step of Parabolic SAR indicator.
void Step(
double step // Step
)
Parameters
step
[in] The value of Step of Parabolic SAR indicator.
Maximum
Sets the value of maximum of Parabolic SAR indicator.
void Maximum(
double maximum // Maximum
)
Parameters
maximum
[in] The value of maximum of Parabolic SAR indicator.
InitIndicators
Initializes indicators and time series.
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Returned value
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
The first it calculates the maximal allowed Stop Loss price, closest to the current price and
calculates Stop Loss price using the values of Parabolic SAR indicator of the previous (completed)
bar.
If position already has Stop Loss price, its value is assumed as a base price, overwise the position
open price is assumed as a base price.
If the calculated Stop Loss price is higher than base price and lower than maximal allowed Stop Loss
price, it suggests to set new Stop Loss price.
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Returned value
Note
The first it calculates the minimal allowed Stop Loss price, closest to the current price and
calculates Stop Loss price using the values of Parabolic SAR indicator of the previous (completed)
bar.
If position already has Stop Loss price, its value is assumed as a base price, overwise the position
open price is assumed as a base price.
If the calculated Stop Loss price is higher than base price and lower than minimal allowed Stop Loss
price, it suggests to set new Stop Loss price.
The use of these classes will save time when creating (and testing) of trading strategies.
MQL5 Standard Library (in terms of money and risk management classes) is placed in the terminal
directory, in the Include\Expert\Money\ folder.
Class Description
CMoneyFixedLot
CMoneyFixedLot is the class money management algorithm, based on trading with predefined fixed lot
size.
Description
CMoneyFixedLot implements money management algorithm, based on trading with predefined fixed
lot size.
Declaration
class CMoneyFixedLot: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedLot.mqh>
Class Methods
Initialization
Lots
Sets trading volume (in lots).
void Lots(
double lots // Lots
)
Parameters
lots
[in] Trading volume (in lots).
ValidationSettings
Checks the settings.
Returned value
Note
CheckOpenLong
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function always returns the fixed trade volume, defined by Lots method.
CheckOpenShort
Gets trade volume for short position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function always returns the fixed trade volume, defined by Lots method.
CMoneyFixedMargin
CMoneyFixedMargin is the class money management algorithm, based on trading with predefined
fixed margin.
Description
Declaration
class CMoneyFixedMargin: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedMargin.mqh>
Class Methods
CheckOpenLong
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for long position, it uses the fixed margin. The margin is defined
by Percent parameter of CExpertMoney base class.
CheckOpenShort
Gets trade volume for short position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for short position, it uses the fixed margin. The margin is
defined by Percent parameter of CExpertMoney base class.
CMoneyFixedRisk
CMoneyFixedRisk is a class with implementation of money management algorithm with fixed
predefined risk.
Description
CMoneyFixedRisk class implements the money management algorithm with fixed predefined risk.
Declaration
class CMoneyFixedRisk: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedRisk.mqh>
Class Methods
CheckOpenLong
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for long position, it uses the fixed risk. The risk is defined by
Percent parameter of CExpertMoney base class.
CheckOpenShort
Gets trade volume for short position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for short position, it uses the fixed risk. The risk is defined by
Percent parameter of CExpertMoney base class.
CMoneyNone
CMoneyNone is a class with implementation of trading algorithm with minimal allowed lot.
Description
Declaration
class CMoneyNone: public CExpertMoney
Title
#include <Expert\Money\MoneyNone.mqh>
Class Methods
Initialization
ValidationSettings
Checks the settings.
Returned value
Note
CheckOpenLong
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
CheckOpenShort
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
CMoneySizeOptimized
CMoneySizeOptimized is a class with implementation of money management algorithm, based on
trading with variable lot size, depending on results of the previous deals.
Description
CMoneySizeOptimized implements money management algorithm, based on trading with variable lot
size, depending on results of the previous deals.
Declaration
class CMoneySizeOptimized: public CExpertMoney
Title
#include <Expert\Money\MoneySizeOptimized.mqh>
Class Methods
Initialization
DecreaseFactor
Sets the value of decrease factor.
void DecreaseFactor(
double decrease_factor // Decrease factor
)
Parameters
decrease_factor
[in] Decrease factor.
Note
The DecreaseFactor defines the volume decreasing coefficient (compared with the volume of
previous position) for the case of consecutive loss trades.
ValidationSettings
Checks the settings.
Returned value
Note
If the value of decrease factor is negative, it returns false, overwise it returns true.
CheckOpenLong
Gets trade volume for long position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for long position, the volume dependent on results of the
previous deals.
CheckOpenShort
Gets trade volume for short position.
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Returned value
Note
The function returns trade volume for short position, the volume dependent on results of the
previous deals.
This section contains information intended to facilitate the adaptation of codes to the new MQL5
language for programmers who know MQL4.
The new language does not contain functions start(), init() and deinit();
The number of indicator buffers is not limited;
dll is downloaded immediately after downloading an Expert Advisor (or any other mql5 program);
Check of logical conditions is shortened;
When limits of an array are exceeded, the current performance is terminated (critically - with the
output of an errors);
Precedence of operators like in C + +;
The language offers the implicit type cast (even from string to a number);
Local variables are not initialized automatically (except for strings);
Common local arrays are automatically deleted.
MQL4 MQL5
init OnInit
start OnStart
deinit OnDeinit
Functions OnInit and OnDeinit perform the same role as init and deinit in MQL4 - they are designed to
locate the code, which must be performed during initialization and deinitialization of mql5 programs.
You can either just rename these functions accordingly, or leave them as they are, but add calls of
these functions in corresponding places.
Example:
void OnInit()
{
//--- Functions is called to initialize
init();
}
The start function is replaced by OnStart only in scripts. In Expert Advisors and indicators it should be
renamed to OnTick and OnCalculate, respectively. The code that is to be executed during a mql5
program operation should be located in these three functions:
script OnStart
indicator OnCalculate
If the indicator or script code does not contain the main function, or the function name differs from
the required one, the call of this function is not performed. It means, if the source code of a script
doesn't contain OnStart, such a code will be compiled as an Expert Advisor.
If an indicator code doesn't contain the OnCalculate function, the compilation of such an indicator is
impossible.
Predefined Variables
In MQL5 there are no such predefined variables as Ask, Bid, Bars. Variables Point and Digits have a
slightly different spelling:
MQL4 MQL5
Digits _Digits
Point _Point
_LastError
_Period
_Symbol
_StopFlag
_UninitReason
Access to Timeseries
In MQL5 there are no such predefined timeseries as Open [], High [], Low [], Close [], Volume [] and
Time []. The necessary depth of a timeseries can now be set using corresponding functions to access
timeseries.
Expert Advisors
Expert Advisors in MQL5 do not require the obligatory presence of the function for handling the events
of a new tick receipt - OnTick, as it was in MQL4 (the start function in MQL4 is executed when you
receive a new tick), because in MQL5 Expert Advisors can contain pre-defined handler functions are
several types of events:
Custom Indicators
In MQL4, the number of indicator buffers is limited and can't exceed 8. In MQL5 there are no such
limitations, but it should be remembered that each indicator buffer requires allocation of a certain
part of memory for its location in the terminal, so the new possibility should not be abused.
MQL4 offered only 6 types of custom indicator plotting; while MQL5 now offers 18 drawing styles. The
names of drawing types haven't changed, but the ideology of the graphical representation of indicators
has changed significantly.
The direction of indexing in indicator buffers also differs. By default, in MQL5 all the indicator buffers
have the behavior of common arrays, i.e. 0 indexed element is the oldest one in the history, and as
the index increases, we move from the oldest data to the most recent ones.
The only function for working with custom indicators that was preserved from MQL4 is SetIndexBuffer.
But its call has changed; now you should specify type of data to be stored in an array, linked to the
indicator buffer.
Properties of custom indicators also have changed and expanded. New functions for accessing
timeseries have been added, so the total calculation algorithm must be reconsidered.
Graphical Objects
The number of graphical objects in has increased significantly MQL5. Besides, graphical objects can
now be positioned in time with the accuracy of a second in a chart of any timeframe - now object
anchor points are not rounded off to the bar opening time in the current price chart.
For objects Arrow, Text and Label now way of binding can be indicated, and for Label, Button, Chart,
Bitmap Label and Edit chart corner, to which the object is anchored, can be set.