MQL 5
MQL 5
Content
Content
51
MQL5 Reference
1 Language Basics................................................................................................. 53
............................................................................................................................54
Sy ntax
Comments......................................................................................................................... 55
Identifiers......................................................................................................................... 56
Reserved .........................................................................................................................
Words
57
Data Ty pes ............................................................................................................................59
Integer Types
......................................................................................................................... 60
Char, Short, Int
................................................................................................................
and Long Types
61
Character Constants
................................................................................................................ 65
Datetime Type
................................................................................................................ 68
Color Type ................................................................................................................ 69
Bool Type
................................................................................................................ 70
Enumerations................................................................................................................ 71
Real Types.........................................................................................................................
(double, float)
73
String Type
......................................................................................................................... 78
Structures.........................................................................................................................
and Classes
79
Dynamic Array
.........................................................................................................................
Object
90
Typecasting
......................................................................................................................... 91
Void Type.........................................................................................................................
and NULL Constant
98
Object Pointers
......................................................................................................................... 99
References:
.........................................................................................................................
Modifier & and Keyword this
102
Operations............................................................................................................................104
and Expressions
Expressions
......................................................................................................................... 105
Arithmetic
.........................................................................................................................
Operations
106
Assignment
.........................................................................................................................
Operations
107
Operations
.........................................................................................................................
of Relation
108
Boolean Operations
......................................................................................................................... 109
Bitwise Operations
......................................................................................................................... 111
Other Operations
......................................................................................................................... 114
Precedence
.........................................................................................................................
Rules
118
Operators ............................................................................................................................120
Compound
.........................................................................................................................
Operator
122
Expression
.........................................................................................................................
Operator
123
Return Operator
......................................................................................................................... 124
Conditional
.........................................................................................................................
Operator if-else
125
Ternary .........................................................................................................................
Operator ?:
126
Switch Operator
......................................................................................................................... 128
Loop Operator
.........................................................................................................................
while
130
Loop Operator
.........................................................................................................................
for
131
Loop Operator
.........................................................................................................................
do while
132
Break Operator
......................................................................................................................... 133
Continue.........................................................................................................................
Operator
134
Object Create
.........................................................................................................................
Operator new
135
Object Delete
.........................................................................................................................
Operator delete
136
Functions ............................................................................................................................137
Function.........................................................................................................................
Call
139
Passing Parameters
......................................................................................................................... 140
Function.........................................................................................................................
Overloading
143
Operation
.........................................................................................................................
Overloading
146
Description
.........................................................................................................................
of External Functions
159
Exporting
.........................................................................................................................
Functions
161
Event Handling
.........................................................................................................................
Functions
162
2000-2016, MetaQuotes Software Corp.
Content
V ariables ............................................................................................................................173
Local Variables
......................................................................................................................... 175
Formal Parameters
......................................................................................................................... 177
Static Variables
......................................................................................................................... 179
Global Variables
......................................................................................................................... 181
Input Variables
......................................................................................................................... 182
Extern Variables
......................................................................................................................... 186
Initialization
.........................................................................................................................
of Variables
187
Visibility .........................................................................................................................
Scope and Lifetime of Variables
189
Creating.........................................................................................................................
and Deleting Objects
191
............................................................................................................................194
Preprocessor
Macro substitution
.........................................................................................................................
(#define)
195
Program.........................................................................................................................
Properties (#property)
198
Including.........................................................................................................................
Files (#include)
203
Importing
.........................................................................................................................
Functions (#import)
204
Conditional
.........................................................................................................................
Compilation (#ifdef, #ifndef, #else, #endif)
206
............................................................................................................................208
Object-Oriented
Programming
Encapsulation
.........................................................................................................................
and Extensibility of Types
210
Inheritance
......................................................................................................................... 213
Polymorphism
......................................................................................................................... 218
Overload......................................................................................................................... 222
Virtual Functions
......................................................................................................................... 223
Static Members
.........................................................................................................................
of a Class
226
Function.........................................................................................................................
templates
230
Abstract.........................................................................................................................
Classes
234
Standard Constants,
.................................................................................................
Enumerations and Structures
236
............................................................................................................................237
Chart Constants
Types of .........................................................................................................................
Chart Events
238
Chart Timeframes
......................................................................................................................... 244
Chart Properties
......................................................................................................................... 246
Positioning
.........................................................................................................................
Constants
252
Chart Representation
......................................................................................................................... 253
Examples.........................................................................................................................
of Working with the Chart
255
............................................................................................................................312
Objects Constants
Object Types
......................................................................................................................... 313
OBJ_VLINE ................................................................................................................ 315
OBJ_HLINE ................................................................................................................ 320
OBJ_TREND ................................................................................................................ 325
OBJ_TRENDBYANGLE
................................................................................................................ 332
OBJ_CYCLES................................................................................................................ 338
OBJ_ARROWED_LINE
................................................................................................................ 344
OBJ_CHANNEL
................................................................................................................ 350
OBJ_STDDEVCHANNEL
................................................................................................................ 357
OBJ_REGRESSION
................................................................................................................ 364
OBJ_PITCHFORK
................................................................................................................ 370
OBJ_GANNLINE
................................................................................................................ 378
OBJ_GANNFAN
................................................................................................................ 385
OBJ_GANNGRID
................................................................................................................ 392
OBJ_FIBO ................................................................................................................ 399
OBJ_FIBOTIMES
................................................................................................................ 406
OBJ_FIBOFAN
................................................................................................................ 413
OBJ_FIBOARC
................................................................................................................ 420
OBJ_FIBOCHANNEL
................................................................................................................ 427
OBJ_EXPANSION
................................................................................................................ 435
OBJ_ELLIOTWAVE5
................................................................................................................ 443
OBJ_ELLIOTWAVE3
................................................................................................................ 451
OBJ_RECTANGLE
................................................................................................................ 458
OBJ_TRIANGLE
................................................................................................................ 464
2000-2016, MetaQuotes Software Corp.
Content
OBJ_ELLIPSE................................................................................................................ 471
OBJ_ARROW_THUMB_UP
................................................................................................................ 477
OBJ_ARROW_THUMB_DOWN
................................................................................................................ 483
OBJ_ARROW_UP
................................................................................................................ 489
OBJ_ARROW_DOWN
................................................................................................................ 495
OBJ_ARROW_STOP
................................................................................................................ 501
OBJ_ARROW_CHECK
................................................................................................................ 507
OBJ_ARROW_LEFT_PRICE
................................................................................................................ 513
OBJ_ARROW_RIGHT_PRICE
................................................................................................................ 518
OBJ_ARROW_BUY
................................................................................................................ 523
OBJ_ARROW_SELL
................................................................................................................ 528
OBJ_ARROW................................................................................................................ 533
OBJ_TEXT ................................................................................................................ 539
OBJ_LABEL ................................................................................................................ 545
OBJ_BUTTON
................................................................................................................ 553
OBJ_CHART ................................................................................................................ 560
OBJ_BITMAP................................................................................................................ 567
OBJ_BITMAP_LABEL
................................................................................................................ 574
OBJ_EDIT ................................................................................................................ 581
OBJ_EVENT ................................................................................................................ 588
OBJ_RECTANGLE_LABEL
................................................................................................................ 593
Object Properties
......................................................................................................................... 599
Methods .........................................................................................................................
of Object Binding
607
Chart Corner
......................................................................................................................... 612
Visibility .........................................................................................................................
of Objects
615
Levels of.........................................................................................................................
Elliott Wave
618
Gann Objects
......................................................................................................................... 619
Web Colors
......................................................................................................................... 621
Wingdings
......................................................................................................................... 623
............................................................................................................................624
Indicator Constants
Price Constants
......................................................................................................................... 625
Smoothing
.........................................................................................................................
Methods
628
Indicators
.........................................................................................................................
Lines
629
Drawing .........................................................................................................................
Styles
631
Custom Indicator
.........................................................................................................................
Properties
635
Indicator.........................................................................................................................
Types
638
Data Type
.........................................................................................................................
Identifiers
640
............................................................................................................................641
Environment
State
Client Terminal
.........................................................................................................................
Properties
642
Running MQL5
.........................................................................................................................
Program Properties
646
Symbol Properties
......................................................................................................................... 649
Account .........................................................................................................................
Properties
662
Testing Statistics
......................................................................................................................... 666
............................................................................................................................670
Trade Constants
History Database
.........................................................................................................................
Properties
671
Order Properties
......................................................................................................................... 672
Position .........................................................................................................................
Properties
676
Deal Properties
......................................................................................................................... 678
Trade Operation
.........................................................................................................................
Types
681
Trade Transaction
.........................................................................................................................
Types
682
Trade Orders
.........................................................................................................................
in DOM
685
Signal Properties
......................................................................................................................... 686
............................................................................................................................688
Named Constants
Predefined
.........................................................................................................................
Macro Substitutions
689
Mathematical
.........................................................................................................................
Constants
691
Numerical
.........................................................................................................................
Type Constants
693
Uninitialization
.........................................................................................................................
Reason Codes
696
Checking.........................................................................................................................
Object Pointer
698
2000-2016, MetaQuotes Software Corp.
Content
Other Constants
......................................................................................................................... 699
............................................................................................................................703
Data Structures
Structure
.........................................................................................................................
of the Date Type
704
Structure
.........................................................................................................................
of Input Parameters
705
History Data
.........................................................................................................................
Structure
706
DOM Structure
......................................................................................................................... 707
Trade Request
.........................................................................................................................
Structure
708
Structure
.........................................................................................................................
of Request Check Results
712
Structure
.........................................................................................................................
of a Trade Request Result
713
Structure
.........................................................................................................................
of a Trade Transaction
717
Structure
.........................................................................................................................
for Current Prices
725
............................................................................................................................726
Codes of Errors
and W arnings
Trade Server
.........................................................................................................................
Return Codes
727
Compiler.........................................................................................................................
Warnings
729
Compilation
.........................................................................................................................
Errors
733
Runtime .........................................................................................................................
Errors
744
............................................................................................................................753
Input/Output
Constants
File Opening
.........................................................................................................................
Flags
754
File Properties
......................................................................................................................... 756
In-File Position
......................................................................................................................... 757
Use of a .........................................................................................................................
Codepage
758
MessageBox
......................................................................................................................... 759
MQL5 programs
................................................................................................. 761
............................................................................................................................762
Program Running
............................................................................................................................768
Trade Permission
............................................................................................................................772
Client Terminal
Events
Resources ............................................................................................................................775
............................................................................................................................784
Call of Imported
Functions
............................................................................................................................786
Runtime Errors
............................................................................................................................787
Testing Trading
Strategies
Predefined Variables
................................................................................................. 812
............................................................................................................................813
_Digits
............................................................................................................................814
_Point
_LastError ............................................................................................................................815
............................................................................................................................816
_Period
............................................................................................................................817
_RandomSeed
_StopFlag ............................................................................................................................818
_Sy mbol ............................................................................................................................819
............................................................................................................................820
_UninitReason
Common Functions
................................................................................................. 821
............................................................................................................................823
Alert
............................................................................................................................824
CheckPointer
Comment ............................................................................................................................826
............................................................................................................................827
Cry ptEncode
............................................................................................................................829
Cry ptDecode
............................................................................................................................830
DebugBreak
............................................................................................................................831
ExpertRemove
GetPointer ............................................................................................................................833
............................................................................................................................837
GetTickCount
............................................................................................................................838
GetMicrosecondCount
MessageBox............................................................................................................................840
............................................................................................................................841
PeriodSeconds
Play Sound ............................................................................................................................842
............................................................................................................................843
Print
PrintFormat............................................................................................................................845
............................................................................................................................851
ResetLastError
............................................................................................................................852
ResourceCreate
2000-2016, MetaQuotes Software Corp.
Content
............................................................................................................................854
ResourceFree
............................................................................................................................855
ResourceReadImage
............................................................................................................................856
ResourceSave
............................................................................................................................857
SetUserError
SendFTP ............................................................................................................................858
............................................................................................................................859
SendNotification
SendMail ............................................................................................................................860
............................................................................................................................861
Sleep
............................................................................................................................862
TerminalClose
............................................................................................................................864
TesterStatistics
............................................................................................................................865
TesterW ithdraw
al
............................................................................................................................866
W ebRequest
............................................................................................................................872
ZeroMemory
Array Functions
................................................................................................. 873
............................................................................................................................874
Array Bsearch
Array Copy ............................................................................................................................878
............................................................................................................................883
Array Compare
Array Free ............................................................................................................................884
............................................................................................................................893
Array GetAsSeries
............................................................................................................................896
Array Initialize
Array Fill ............................................................................................................................898
............................................................................................................................900
Array IsDy namic
............................................................................................................................902
Array IsSeries
............................................................................................................................904
Array Maximum
............................................................................................................................915
Array Minimum
Array Range............................................................................................................................926
............................................................................................................................927
Array Resize
............................................................................................................................930
Array SetAsSeries
Array Size ............................................................................................................................933
Array Sort ............................................................................................................................935
Conversion Functions
................................................................................................. 940
............................................................................................................................942
CharToString
............................................................................................................................943
CharArray ToString
............................................................................................................................944
ColorToARGB
............................................................................................................................946
ColorToString
............................................................................................................................947
DoubleToString
............................................................................................................................948
EnumToString
............................................................................................................................950
IntegerToString
............................................................................................................................951
ShortToString
ShortArray............................................................................................................................952
ToString
............................................................................................................................953
TimeToString
............................................................................................................................954
NormalizeDouble
............................................................................................................................956
StringToCharArray
............................................................................................................................957
StringToColor
............................................................................................................................958
StringToDouble
............................................................................................................................959
StringToInteger
............................................................................................................................960
StringToShortArray
............................................................................................................................961
StringToTime
............................................................................................................................962
StringFormat
Math Functions
................................................................................................. 966
MathAbs ............................................................................................................................967
MathArccos............................................................................................................................968
MathArcsin............................................................................................................................969
MathArctan............................................................................................................................970
MathCeil ............................................................................................................................971
MathCos ............................................................................................................................972
MathExp ............................................................................................................................973
2000-2016, MetaQuotes Software Corp.
Content
MathFloor ............................................................................................................................974
MathLog ............................................................................................................................975
MathLog10 ............................................................................................................................976
MathMax ............................................................................................................................977
MathMin ............................................................................................................................978
MathMod ............................................................................................................................979
MathPow ............................................................................................................................980
MathRand ............................................................................................................................981
MathRound............................................................................................................................982
............................................................................................................................983
MathSin
MathSqrt ............................................................................................................................984
MathSrand ............................................................................................................................985
MathTan ............................................................................................................................988
............................................................................................................................989
MathIsV alidNumber
String Functions
................................................................................................. 990
StringAdd ............................................................................................................................991
............................................................................................................................993
StringBufferLen
............................................................................................................................994
StringCompare
............................................................................................................................996
StringConcatenate
StringFill ............................................................................................................................997
StringFind ............................................................................................................................998
............................................................................................................................999
StringGetCharacter
StringInit ............................................................................................................................1000
StringLen ............................................................................................................................1001
............................................................................................................................1002
StringReplace
............................................................................................................................1003
StringSetCharacter
StringSplit............................................................................................................................1005
............................................................................................................................1007
StringSubstr
............................................................................................................................1008
StringToLow
er
............................................................................................................................1009
StringToUpper
............................................................................................................................1010
StringTrimLeft
............................................................................................................................1011
StringTrimRight
10
11 Account Information
................................................................................................. 1021
............................................................................................................................1022
AccountInfoDouble
............................................................................................................................1023
AccountInfoInteger
............................................................................................................................1025
AccountInfoString
12
Checkup
................................................................................................. 1026
............................................................................................................................1027
GetLastError
IsStopped............................................................................................................................1028
............................................................................................................................1029
UninitializeReason
............................................................................................................................1030
TerminalInfoInteger
............................................................................................................................1031
TerminalInfoDouble
............................................................................................................................1032
TerminalInfoString
............................................................................................................................1033
MQLInfoInteger
............................................................................................................................1034
MQLInfoString
Sy mbol ............................................................................................................................1035
............................................................................................................................1036
Period
............................................................................................................................1037
Digits
2000-2016, MetaQuotes Software Corp.
Content
Point
13
............................................................................................................................1038
14
Timeseries and
.................................................................................................
Indicators Access
1056
............................................................................................................................1060
Indexing Direction
in Array s, Buffers and Timeseries
Organizing............................................................................................................................1063
Data Access
............................................................................................................................1072
SeriesInfoInteger
............................................................................................................................1074
Bars
............................................................................................................................1076
BarsCalculated
............................................................................................................................1078
IndicatorCreate
............................................................................................................................1080
IndicatorParameters
............................................................................................................................1082
IndicatorRelease
............................................................................................................................1084
Copy Buffer
Copy Rates............................................................................................................................1089
Copy Time............................................................................................................................1093
Copy Open............................................................................................................................1096
Copy High ............................................................................................................................1099
Copy Low ............................................................................................................................1103
Copy Close............................................................................................................................1106
............................................................................................................................1109
Copy TickV
olume
Copy RealV............................................................................................................................1113
olume
............................................................................................................................1116
Copy Spread
Copy Ticks............................................................................................................................1120
15
Chart Operations
................................................................................................. 1122
............................................................................................................................1124
ChartApply
Template
............................................................................................................................1127
ChartSaveTemplate
............................................................................................................................1132
ChartW indow
Find
............................................................................................................................1134
ChartTimePriceToX
Y
............................................................................................................................1135
ChartX Y ToTimePrice
ChartOpen............................................................................................................................1137
ChartFirst ............................................................................................................................1138
ChartNext............................................................................................................................1139
ChartClose............................................................................................................................1140
............................................................................................................................1141
ChartSy mbol
............................................................................................................................1142
ChartPeriod
............................................................................................................................1143
ChartRedraw
............................................................................................................................1144
ChartSetDouble
............................................................................................................................1145
ChartSetInteger
............................................................................................................................1146
ChartSetString
............................................................................................................................1147
ChartGetDouble
............................................................................................................................1149
ChartGetInteger
............................................................................................................................1151
ChartGetString
............................................................................................................................1153
ChartNavigate
ChartID ............................................................................................................................1156
2000-2016, MetaQuotes Software Corp.
Content
............................................................................................................................1157
ChartIndicatorAdd
............................................................................................................................1161
ChartIndicatorDelete
............................................................................................................................1164
ChartIndicatorGet
............................................................................................................................1166
ChartIndicatorName
............................................................................................................................1167
ChartIndicatorsTotal
............................................................................................................................1168
ChartW indow
OnDropped
............................................................................................................................1169
ChartPriceOnDropped
............................................................................................................................1170
ChartTimeOnDropped
............................................................................................................................1171
ChartX OnDropped
............................................................................................................................1172
ChartY OnDropped
ChartSetSy............................................................................................................................1173
mbolPeriod
............................................................................................................................1174
ChartScreenShot
16
Trade Functions
................................................................................................. 1177
............................................................................................................................1179
OrderCalcMargin
............................................................................................................................1180
OrderCalcProfit
............................................................................................................................1181
OrderCheck
............................................................................................................................1182
OrderSend
............................................................................................................................1187
OrderSendAsy
nc
............................................................................................................................1198
PositionsTotal
............................................................................................................................1199
PositionGetSy
mbol
............................................................................................................................1200
PositionSelect
............................................................................................................................1201
PositionSelectBy
Ticket
............................................................................................................................1202
PositionGetDouble
............................................................................................................................1203
PositionGetInteger
............................................................................................................................1205
PositionGetString
............................................................................................................................1206
PositionGetTicket
............................................................................................................................1207
OrdersTotal
............................................................................................................................1208
OrderGetTicket
............................................................................................................................1210
OrderSelect
............................................................................................................................1211
OrderGetDouble
............................................................................................................................1212
OrderGetInteger
............................................................................................................................1213
OrderGetString
............................................................................................................................1214
History Select
............................................................................................................................1216
History SelectBy
Position
............................................................................................................................1217
History OrderSelect
............................................................................................................................1218
History OrdersTotal
............................................................................................................................1219
History OrderGetTicket
............................................................................................................................1221
History OrderGetDouble
............................................................................................................................1222
History OrderGetInteger
............................................................................................................................1225
History OrderGetString
............................................................................................................................1226
History DealSelect
............................................................................................................................1227
History DealsTotal
............................................................................................................................1228
History DealGetTicket
............................................................................................................................1230
History DealGetDouble
............................................................................................................................1231
History DealGetInteger
............................................................................................................................1234
History DealGetString
17
10
Content
............................................................................................................................1247
SignalUnSubscribe
18
Global Variables
.................................................................................................
of the Terminal
1248
............................................................................................................................1249
GlobalV ariableCheck
............................................................................................................................1250
GlobalV ariableTime
............................................................................................................................1251
GlobalV ariableDel
............................................................................................................................1252
GlobalV ariableGet
............................................................................................................................1253
GlobalV ariableName
............................................................................................................................1254
GlobalV ariableSet
............................................................................................................................1255
GlobalV ariablesFlush
............................................................................................................................1256
GlobalV ariableTemp
............................................................................................................................1257
GlobalV ariableSetOnCondition
............................................................................................................................1258
GlobalV ariablesDeleteAll
............................................................................................................................1259
GlobalV ariablesTotal
19
File Functions
................................................................................................. 1260
............................................................................................................................1263
FileFindFirst
............................................................................................................................1265
FileFindNext
............................................................................................................................1267
FileFindClose
FileIsExist ............................................................................................................................1269
FileOpen ............................................................................................................................1272
FileClose ............................................................................................................................1275
FileCopy ............................................................................................................................1276
FileDelete............................................................................................................................1279
FileMove ............................................................................................................................1281
FileFlush ............................................................................................................................1283
............................................................................................................................1285
FileGetInteger
............................................................................................................................1288
FileIsEnding
............................................................................................................................1290
FileIsLineEnding
............................................................................................................................1295
FileReadArray
............................................................................................................................1297
FileReadBool
............................................................................................................................1300
FileReadDatetime
............................................................................................................................1303
FileReadDouble
............................................................................................................................1306
FileReadFloat
............................................................................................................................1309
FileReadInteger
............................................................................................................................1313
FileReadLong
............................................................................................................................1316
FileReadNumber
............................................................................................................................1321
FileReadString
............................................................................................................................1323
FileReadStruct
FileSeek ............................................................................................................................1327
FileSize ............................................................................................................................1330
FileTell ............................................................................................................................1332
FileW rite ............................................................................................................................1335
............................................................................................................................1338
FileW riteArray
............................................................................................................................1341
FileW riteDouble
............................................................................................................................1344
FileW riteFloat
............................................................................................................................1346
FileW riteInteger
............................................................................................................................1349
FileW riteLong
............................................................................................................................1351
FileW riteString
............................................................................................................................1354
FileW riteStruct
............................................................................................................................1357
FolderCreate
............................................................................................................................1360
FolderDelete
............................................................................................................................1363
FolderClean
20
Custom Indicators
................................................................................................. 1366
............................................................................................................................1370
Indicator Sty
les in Examples
DRAW_NONE
......................................................................................................................... 1377
DRAW_LINE
......................................................................................................................... 1380
DRAW_SECTION
......................................................................................................................... 1384
DRAW_HISTOGRAM
......................................................................................................................... 1388
2000-2016, MetaQuotes Software Corp.
11
Content
DRAW_HISTOGRAM2
......................................................................................................................... 1392
DRAW_ARROW
......................................................................................................................... 1396
DRAW_ZIGZAG
......................................................................................................................... 1401
DRAW_FILLING
......................................................................................................................... 1406
DRAW_BARS
......................................................................................................................... 1411
DRAW_CANDLES
......................................................................................................................... 1417
DRAW_COLOR_LINE
......................................................................................................................... 1423
DRAW_COLOR_SECTION
......................................................................................................................... 1428
DRAW_COLOR_HISTOGRAM
......................................................................................................................... 1434
DRAW_COLOR_HISTOGRAM2
......................................................................................................................... 1439
DRAW_COLOR_ARROW
......................................................................................................................... 1444
DRAW_COLOR_ZIGZAG
......................................................................................................................... 1450
DRAW_COLOR_BARS
......................................................................................................................... 1455
DRAW_COLOR_CANDLES
......................................................................................................................... 1462
............................................................................................................................1469
Connection
betw een Indicator Properties and Functions
............................................................................................................................1471
SetIndexBuffer
............................................................................................................................1474
IndicatorSetDouble
............................................................................................................................1477
IndicatorSetInteger
............................................................................................................................1481
IndicatorSetString
............................................................................................................................1484
PlotIndexSetDouble
............................................................................................................................1485
PlotIndexSetInteger
............................................................................................................................1489
PlotIndexSetString
............................................................................................................................1490
PlotIndexGetInteger
21 Object Functions
................................................................................................. 1493
............................................................................................................................1495
ObjectCreate
............................................................................................................................1499
ObjectName
............................................................................................................................1500
ObjectDelete
............................................................................................................................1501
ObjectsDeleteAll
............................................................................................................................1502
ObjectFind
............................................................................................................................1503
ObjectGetTimeBy
V alue
............................................................................................................................1504
ObjectGetV
alueBy Time
............................................................................................................................1505
ObjectMove
............................................................................................................................1506
ObjectsTotal
............................................................................................................................1507
ObjectSetDouble
............................................................................................................................1510
ObjectSetInteger
............................................................................................................................1513
ObjectSetString
............................................................................................................................1515
ObjectGetDouble
............................................................................................................................1516
ObjectGetInteger
............................................................................................................................1517
ObjectGetString
............................................................................................................................1519
TextSetFont
TextOut ............................................................................................................................1521
............................................................................................................................1525
TextGetSize
22
Technical Indicators
................................................................................................. 1526
............................................................................................................................1528
iAC
............................................................................................................................1533
iAD
............................................................................................................................1538
iADX
............................................................................................................................1543
iADX W ilder
iAlligator ............................................................................................................................1548
............................................................................................................................1555
iAMA
............................................................................................................................1560
iAO
............................................................................................................................1565
iATR
iBearsPow............................................................................................................................1570
er
............................................................................................................................1575
iBands
............................................................................................................................1581
iBullsPow er
............................................................................................................................1586
iCCI
iChaikin ............................................................................................................................1591
iCustom ............................................................................................................................1596
............................................................................................................................1599
iDEMA
2000-2016, MetaQuotes Software Corp.
12
Content
iDeMarker............................................................................................................................1604
iEnvelopes............................................................................................................................1609
............................................................................................................................1615
iForce
iFractals ............................................................................................................................1620
iFrAMA ............................................................................................................................1625
............................................................................................................................1630
iGator
iIchimoku............................................................................................................................1637
iBW MFI ............................................................................................................................1644
............................................................................................................................1649
iMomentum
............................................................................................................................1654
iMFI
............................................................................................................................1659
iMA
............................................................................................................................1664
iOsMA
............................................................................................................................1669
iMACD
............................................................................................................................1675
iOBV
............................................................................................................................1680
iSAR
............................................................................................................................1685
iRSI
............................................................................................................................1690
iRV I
iStdDev ............................................................................................................................1695
iStochastic............................................................................................................................1700
............................................................................................................................1706
iTEMA
............................................................................................................................1711
iTriX
............................................................................................................................1716
iW PR
............................................................................................................................1721
iV IDy A
iV olumes ............................................................................................................................1726
23
Working with.................................................................................................
Optimization Results
1731
FrameFirst............................................................................................................................1732
............................................................................................................................1733
FrameFilter
............................................................................................................................1734
FrameNext
............................................................................................................................1735
FrameInputs
FrameAdd............................................................................................................................1736
............................................................................................................................1737
ParameterGetRange
............................................................................................................................1740
ParameterSetRange
24
Working with.................................................................................................
Events
1742
............................................................................................................................1743
EventSetMillisecondTimer
............................................................................................................................1744
EventSetTimer
............................................................................................................................1745
EventKillTimer
............................................................................................................................1746
EventChartCustom
25
Working with.................................................................................................
OpenCL
1752
............................................................................................................................1753
CLHandleTy
pe
............................................................................................................................1754
CLGetInfoInteger
............................................................................................................................1756
CLGetInfoString
............................................................................................................................1759
CLContextCreate
............................................................................................................................1760
CLContextFree
............................................................................................................................1761
CLGetDeviceInfo
............................................................................................................................1765
CLProgramCreate
............................................................................................................................1770
CLProgramFree
............................................................................................................................1771
CLKernelCreate
............................................................................................................................1772
CLKernelFree
............................................................................................................................1773
CLSetKernelArg
............................................................................................................................1774
CLSetKernelArgMem
............................................................................................................................1775
CLBufferCreate
............................................................................................................................1776
CLBufferFree
CLBufferW............................................................................................................................1777
rite
............................................................................................................................1778
CLBufferRead
CLExecute............................................................................................................................1779
26
Standard Library
................................................................................................. 1781
Basic Class............................................................................................................................1782
CObject
2000-2016, MetaQuotes Software Corp.
13
Content
Prev ......................................................................................................................... 1783
Prev ......................................................................................................................... 1784
Next ......................................................................................................................... 1785
Next ......................................................................................................................... 1786
Compare
......................................................................................................................... 1787
Save ......................................................................................................................... 1789
Load ......................................................................................................................... 1791
Type ......................................................................................................................... 1793
Classes of ............................................................................................................................1794
data
CArray ......................................................................................................................... 1795
Step
................................................................................................................ 1797
Step
................................................................................................................ 1798
Total
................................................................................................................ 1799
Available ................................................................................................................ 1800
Max
................................................................................................................ 1801
IsSorted ................................................................................................................ 1802
SortMode ................................................................................................................ 1803
Clear
................................................................................................................ 1804
Sort
................................................................................................................ 1805
Save
................................................................................................................ 1806
Load
................................................................................................................ 1807
CArrayChar
......................................................................................................................... 1808
Reserve ................................................................................................................ 1810
Resize
................................................................................................................ 1811
Shutdown ................................................................................................................ 1812
Add
................................................................................................................ 1813
AddArray ................................................................................................................ 1814
AddArray ................................................................................................................ 1815
Insert
................................................................................................................ 1817
InsertArray................................................................................................................ 1818
InsertArray................................................................................................................ 1819
AssignArray................................................................................................................ 1821
AssignArray................................................................................................................ 1822
Update
................................................................................................................ 1824
Shift
................................................................................................................ 1825
Delete
................................................................................................................ 1826
DeleteRange
................................................................................................................ 1827
At
................................................................................................................ 1828
CompareArray
................................................................................................................ 1830
CompareArray
................................................................................................................ 1831
InsertSort ................................................................................................................ 1832
Search
................................................................................................................ 1833
SearchGreat
................................................................................................................ 1834
SearchLess................................................................................................................ 1835
SearchGreatOrEqual
................................................................................................................ 1836
SearchLessOrEqual
................................................................................................................ 1837
SearchFirst................................................................................................................ 1838
SearchLast................................................................................................................ 1839
SearchLinear
................................................................................................................ 1840
Save
................................................................................................................ 1841
Load
................................................................................................................ 1842
Type
................................................................................................................ 1844
CArrayShort
......................................................................................................................... 1845
Reserve ................................................................................................................ 1847
Resize
................................................................................................................ 1848
Shutdown ................................................................................................................ 1849
Add
................................................................................................................ 1850
AddArray ................................................................................................................ 1851
2000-2016, MetaQuotes Software Corp.
14
Content
AddArray ................................................................................................................ 1852
Insert
................................................................................................................ 1854
InsertArray................................................................................................................ 1855
InsertArray................................................................................................................ 1856
AssignArray................................................................................................................ 1858
AssignArray................................................................................................................ 1859
Update
................................................................................................................ 1861
Shift
................................................................................................................ 1862
Delete
................................................................................................................ 1863
DeleteRange
................................................................................................................ 1864
At
................................................................................................................ 1865
CompareArray
................................................................................................................ 1867
CompareArray
................................................................................................................ 1868
InsertSort ................................................................................................................ 1869
Search
................................................................................................................ 1870
SearchGreat
................................................................................................................ 1871
SearchLess................................................................................................................ 1872
SearchGreatOrEqual
................................................................................................................ 1873
SearchLessOrEqual
................................................................................................................ 1874
SearchFirst................................................................................................................ 1875
SearchLast................................................................................................................ 1876
SearchLinear
................................................................................................................ 1877
Save
................................................................................................................ 1878
Load
................................................................................................................ 1880
Type
................................................................................................................ 1882
CArrayInt
......................................................................................................................... 1883
Reserve ................................................................................................................ 1885
Resize
................................................................................................................ 1886
Shutdown ................................................................................................................ 1887
Add
................................................................................................................ 1888
AddArray ................................................................................................................ 1889
AddArray ................................................................................................................ 1890
Insert
................................................................................................................ 1892
InsertArray................................................................................................................ 1893
InsertArray................................................................................................................ 1894
AssignArray................................................................................................................ 1896
AssignArray................................................................................................................ 1897
Update
................................................................................................................ 1899
Shift
................................................................................................................ 1900
Delete
................................................................................................................ 1901
DeleteRange
................................................................................................................ 1902
At
................................................................................................................ 1903
CompareArray
................................................................................................................ 1905
CompareArray
................................................................................................................ 1906
InsertSort ................................................................................................................ 1907
Search
................................................................................................................ 1908
SearchGreat
................................................................................................................ 1909
SearchLess................................................................................................................ 1910
SearchGreatOrEqual
................................................................................................................ 1911
SearchLessOrEqual
................................................................................................................ 1912
SearchFirst................................................................................................................ 1913
SearchLast................................................................................................................ 1914
SearchLinear
................................................................................................................ 1915
Save
................................................................................................................ 1916
Load
................................................................................................................ 1918
Type
................................................................................................................ 1920
CArrayLong
......................................................................................................................... 1921
Reserve ................................................................................................................ 1924
2000-2016, MetaQuotes Software Corp.
15
Content
Resize
................................................................................................................ 1925
Shutdown ................................................................................................................ 1926
Add
................................................................................................................ 1927
AddArray ................................................................................................................ 1928
AddArray ................................................................................................................ 1929
Insert
................................................................................................................ 1931
InsertArray................................................................................................................ 1932
InsertArray................................................................................................................ 1933
AssignArray................................................................................................................ 1935
AssignArray................................................................................................................ 1936
Update
................................................................................................................ 1938
Shift
................................................................................................................ 1939
Delete
................................................................................................................ 1940
DeleteRange
................................................................................................................ 1941
At
................................................................................................................ 1942
CompareArray
................................................................................................................ 1944
CompareArray
................................................................................................................ 1945
InsertSort ................................................................................................................ 1946
Search
................................................................................................................ 1947
SearchGreat
................................................................................................................ 1948
SearchLess................................................................................................................ 1949
SearchGreatOrEqual
................................................................................................................ 1950
SearchLessOrEqual
................................................................................................................ 1951
SearchFirst................................................................................................................ 1952
SearchLast................................................................................................................ 1953
SearchLinear
................................................................................................................ 1954
Save
................................................................................................................ 1955
Load
................................................................................................................ 1957
Type
................................................................................................................ 1959
CArrayFloat
......................................................................................................................... 1960
Delta
................................................................................................................ 1963
Reserve ................................................................................................................ 1964
Resize
................................................................................................................ 1965
Shutdown ................................................................................................................ 1966
Add
................................................................................................................ 1967
AddArray ................................................................................................................ 1968
AddArray ................................................................................................................ 1969
Insert
................................................................................................................ 1971
InsertArray................................................................................................................ 1972
InsertArray................................................................................................................ 1973
AssignArray................................................................................................................ 1975
AssignArray................................................................................................................ 1976
Update
................................................................................................................ 1978
Shift
................................................................................................................ 1979
Delete
................................................................................................................ 1980
DeleteRange
................................................................................................................ 1981
At
................................................................................................................ 1982
CompareArray
................................................................................................................ 1984
CompareArray
................................................................................................................ 1985
InsertSort ................................................................................................................ 1986
Search
................................................................................................................ 1987
SearchGreat
................................................................................................................ 1988
SearchLess................................................................................................................ 1989
SearchGreatOrEqual
................................................................................................................ 1990
SearchLessOrEqual
................................................................................................................ 1991
SearchFirst................................................................................................................ 1992
SearchLast................................................................................................................ 1993
SearchLinear
................................................................................................................ 1994
2000-2016, MetaQuotes Software Corp.
16
Content
Save
................................................................................................................ 1995
Load
................................................................................................................ 1997
Type
................................................................................................................ 1999
CArrayDouble
......................................................................................................................... 2000
Delta
................................................................................................................ 2003
Reserve ................................................................................................................ 2004
Resize
................................................................................................................ 2005
Shutdown ................................................................................................................ 2006
Add
................................................................................................................ 2007
AddArray ................................................................................................................ 2008
AddArray ................................................................................................................ 2009
Insert
................................................................................................................ 2011
InsertArray................................................................................................................ 2012
InsertArray................................................................................................................ 2013
AssignArray................................................................................................................ 2015
AssignArray................................................................................................................ 2016
Update
................................................................................................................ 2018
Shift
................................................................................................................ 2019
Delete
................................................................................................................ 2020
DeleteRange
................................................................................................................ 2021
At
................................................................................................................ 2022
CompareArray
................................................................................................................ 2024
CompareArray
................................................................................................................ 2025
Minimum ................................................................................................................ 2026
Maximum ................................................................................................................ 2027
InsertSort ................................................................................................................ 2028
Search
................................................................................................................ 2029
SearchGreat
................................................................................................................ 2030
SearchLess................................................................................................................ 2031
SearchGreatOrEqual
................................................................................................................ 2032
SearchLessOrEqual
................................................................................................................ 2033
SearchFirst................................................................................................................ 2034
SearchLast................................................................................................................ 2035
SearchLinear
................................................................................................................ 2036
Save
................................................................................................................ 2037
Load
................................................................................................................ 2039
Type
................................................................................................................ 2041
CArrayString
......................................................................................................................... 2042
Reserve ................................................................................................................ 2044
Resize
................................................................................................................ 2045
Shutdown ................................................................................................................ 2046
Add
................................................................................................................ 2047
AddArray ................................................................................................................ 2048
AddArray ................................................................................................................ 2049
Insert
................................................................................................................ 2051
InsertArray................................................................................................................ 2052
InsertArray................................................................................................................ 2053
AssignArray................................................................................................................ 2055
AssignArray................................................................................................................ 2056
Update
................................................................................................................ 2058
Shift
................................................................................................................ 2059
Delete
................................................................................................................ 2060
DeleteRange
................................................................................................................ 2061
At
................................................................................................................ 2062
CompareArray
................................................................................................................ 2064
CompareArray
................................................................................................................ 2065
InsertSort ................................................................................................................ 2066
Search
................................................................................................................ 2067
2000-2016, MetaQuotes Software Corp.
17
Content
SearchGreat
................................................................................................................ 2068
SearchLess................................................................................................................ 2069
SearchGreatOrEqual
................................................................................................................ 2070
SearchLessOrEqual
................................................................................................................ 2071
SearchFirst................................................................................................................ 2072
SearchLast................................................................................................................ 2073
SearchLinear
................................................................................................................ 2074
Save
................................................................................................................ 2075
Load
................................................................................................................ 2077
Type
................................................................................................................ 2079
CArrayObj
......................................................................................................................... 2080
FreeMode ................................................................................................................ 2085
FreeMode ................................................................................................................ 2086
Reserve ................................................................................................................ 2088
Resize
................................................................................................................ 2089
Clear
................................................................................................................ 2090
Shutdown ................................................................................................................ 2091
CreateElement
................................................................................................................ 2092
Add
................................................................................................................ 2094
AddArray ................................................................................................................ 2095
Insert
................................................................................................................ 2098
InsertArray................................................................................................................ 2100
AssignArray................................................................................................................ 2102
Update
................................................................................................................ 2104
Shift
................................................................................................................ 2105
Detach
................................................................................................................ 2106
Delete
................................................................................................................ 2107
DeleteRange
................................................................................................................ 2108
At
................................................................................................................ 2109
CompareArray
................................................................................................................ 2110
InsertSort ................................................................................................................ 2111
Search
................................................................................................................ 2112
SearchGreat
................................................................................................................ 2113
SearchLess................................................................................................................ 2114
SearchGreatOrEqual
................................................................................................................ 2115
SearchLessOrEqual
................................................................................................................ 2117
SearchFirst................................................................................................................ 2118
SearchLast................................................................................................................ 2119
Save
................................................................................................................ 2120
Load
................................................................................................................ 2121
Type
................................................................................................................ 2123
CList ......................................................................................................................... 2124
FreeMode ................................................................................................................ 2126
FreeMode ................................................................................................................ 2127
Total
................................................................................................................ 2129
IsSorted ................................................................................................................ 2130
SortMode ................................................................................................................ 2131
CreateElement
................................................................................................................ 2132
Add
................................................................................................................ 2133
Insert
................................................................................................................ 2134
DetachCurrent
................................................................................................................ 2136
DeleteCurrent
................................................................................................................ 2137
Delete
................................................................................................................ 2138
Clear
................................................................................................................ 2139
IndexOf ................................................................................................................ 2140
GetNodeAtIndex
................................................................................................................ 2141
GetFirstNode
................................................................................................................ 2142
GetPrevNode
................................................................................................................ 2143
2000-2016, MetaQuotes Software Corp.
18
Content
GetCurrentNode
................................................................................................................ 2144
GetNextNode
................................................................................................................ 2145
GetLastNode
................................................................................................................ 2146
Sort
................................................................................................................ 2147
MoveToIndex
................................................................................................................ 2148
Exchange ................................................................................................................ 2149
CompareList
................................................................................................................ 2150
Search
................................................................................................................ 2151
Save
................................................................................................................ 2152
Load
................................................................................................................ 2154
Type
................................................................................................................ 2156
CTreeNode
......................................................................................................................... 2157
Owner
................................................................................................................ 2162
Left
................................................................................................................ 2163
Right
................................................................................................................ 2164
Balance ................................................................................................................ 2165
BalanceL ................................................................................................................ 2166
BalanceR ................................................................................................................ 2167
CreateSample
................................................................................................................ 2168
RefreshBalance
................................................................................................................ 2169
GetNext ................................................................................................................ 2170
SaveNode ................................................................................................................ 2171
LoadNode ................................................................................................................ 2172
Type
................................................................................................................ 2173
CTree ......................................................................................................................... 2174
Root
................................................................................................................ 2179
CreateElement
................................................................................................................ 2180
Insert
................................................................................................................ 2181
Detach
................................................................................................................ 2182
Delete
................................................................................................................ 2183
Clear
................................................................................................................ 2184
Find
................................................................................................................ 2185
Save
................................................................................................................ 2186
Load
................................................................................................................ 2187
Type
................................................................................................................ 2188
Classes for............................................................................................................................2189
Graphic Objects
CChartObject
......................................................................................................................... 2190
ChartId ................................................................................................................ 2193
Window ................................................................................................................ 2194
Name
................................................................................................................ 2195
NumPoints ................................................................................................................ 2196
Attach
................................................................................................................ 2197
SetPoint ................................................................................................................ 2198
Delete
................................................................................................................ 2199
Detach
................................................................................................................ 2200
ShiftObject................................................................................................................ 2201
ShiftPoint ................................................................................................................ 2202
Time
................................................................................................................ 2203
Price
................................................................................................................ 2205
Color
................................................................................................................ 2207
Style
................................................................................................................ 2208
Width
................................................................................................................ 2209
Background
................................................................................................................ 2210
Selected ................................................................................................................ 2211
Selectable ................................................................................................................ 2212
Description................................................................................................................ 2213
Tooltip
................................................................................................................ 2214
Timeframes................................................................................................................ 2215
2000-2016, MetaQuotes Software Corp.
19
Content
Z_Order ................................................................................................................ 2216
CreateTime................................................................................................................ 2217
LevelsCount
................................................................................................................ 2218
LevelColor ................................................................................................................ 2219
LevelStyle ................................................................................................................ 2221
LevelWidth................................................................................................................ 2223
LevelValue ................................................................................................................ 2225
LevelDescription
................................................................................................................ 2227
GetInteger................................................................................................................ 2229
SetInteger................................................................................................................ 2231
GetDouble ................................................................................................................ 2233
SetDouble ................................................................................................................ 2235
GetString ................................................................................................................ 2237
SetString ................................................................................................................ 2239
Save
................................................................................................................ 2241
Load
................................................................................................................ 2242
Type
................................................................................................................ 2243
Line Objects
......................................................................................................................... 2244
CChartObjectVLine
................................................................................................................ 2245
Create
........................................................................................................... 2246
Type
........................................................................................................... 2247
CChartObjectHLine
................................................................................................................ 2248
Create
........................................................................................................... 2249
Type
........................................................................................................... 2250
CChartObjectTrend
................................................................................................................ 2251
Create
........................................................................................................... 2252
RayLeft ........................................................................................................... 2253
RayRight ........................................................................................................... 2254
Save
........................................................................................................... 2255
Load
........................................................................................................... 2256
Type
........................................................................................................... 2257
CChartObjectTrendByAngle
................................................................................................................ 2258
Create
........................................................................................................... 2259
Angle
........................................................................................................... 2260
Type
........................................................................................................... 2261
CChartObjectCycles
................................................................................................................ 2262
Create
........................................................................................................... 2263
Type
........................................................................................................... 2264
Channel.........................................................................................................................
Objects
2265
CChartObjectChannel
................................................................................................................ 2266
Create
........................................................................................................... 2267
Type
........................................................................................................... 2268
CChartObjectRegression
................................................................................................................ 2269
Create
........................................................................................................... 2270
Type
........................................................................................................... 2271
CChartObjectStdDevChannel
................................................................................................................ 2272
Create
........................................................................................................... 2273
Deviations........................................................................................................... 2274
Save
........................................................................................................... 2275
Load
........................................................................................................... 2276
Type
........................................................................................................... 2277
CChartObjectPitchfork
................................................................................................................ 2278
Create
........................................................................................................... 2279
Type
........................................................................................................... 2280
Gann Tools
......................................................................................................................... 2281
CChartObjectGannLine
................................................................................................................ 2282
Create
........................................................................................................... 2283
PipsPerBar........................................................................................................... 2284
2000-2016, MetaQuotes Software Corp.
20
Content
Save
........................................................................................................... 2285
Load
........................................................................................................... 2286
Type
........................................................................................................... 2287
CChartObjectGannFan
................................................................................................................ 2288
Create
........................................................................................................... 2289
PipsPerBar........................................................................................................... 2290
Downtrend........................................................................................................... 2291
Save
........................................................................................................... 2292
Load
........................................................................................................... 2293
Type
........................................................................................................... 2294
CChartObjectGannGrid
................................................................................................................ 2295
Create
........................................................................................................... 2296
PipsPerBar........................................................................................................... 2297
Downtrend........................................................................................................... 2298
Save
........................................................................................................... 2299
Load
........................................................................................................... 2300
Type
........................................................................................................... 2301
Fibonacci
.........................................................................................................................
Tools
2302
CChartObjectFibo
................................................................................................................ 2303
Create
........................................................................................................... 2304
Type
........................................................................................................... 2305
CChartObjectFiboTimes
................................................................................................................ 2306
Create
........................................................................................................... 2307
Type
........................................................................................................... 2308
CChartObjectFiboFan
................................................................................................................ 2309
Create
........................................................................................................... 2310
Type
........................................................................................................... 2311
CChartObjectFiboArc
................................................................................................................ 2312
Create
........................................................................................................... 2313
Scale
........................................................................................................... 2314
Ellipse
........................................................................................................... 2315
Save
........................................................................................................... 2316
Load
........................................................................................................... 2317
Type
........................................................................................................... 2318
CChartObjectFiboChannel
................................................................................................................ 2319
Create
........................................................................................................... 2320
Type
........................................................................................................... 2321
CChartObjectFiboExpansion
................................................................................................................ 2322
Create
........................................................................................................... 2323
Type
........................................................................................................... 2324
Elliott Tools
......................................................................................................................... 2325
CChartObjectElliottWave3
................................................................................................................ 2326
Create
........................................................................................................... 2327
Degree
........................................................................................................... 2328
Lines
........................................................................................................... 2329
Save
........................................................................................................... 2330
Load
........................................................................................................... 2331
Type
........................................................................................................... 2332
CChartObjectElliottWave5
................................................................................................................ 2333
Create
........................................................................................................... 2334
Type
........................................................................................................... 2336
Shape Objects
......................................................................................................................... 2337
CChartObjectRectangle
................................................................................................................ 2338
Create
........................................................................................................... 2339
Type
........................................................................................................... 2340
CChartObjectTriangle
................................................................................................................ 2341
Create
........................................................................................................... 2342
Type
........................................................................................................... 2343
2000-2016, MetaQuotes Software Corp.
21
Content
CChartObjectEllipse
................................................................................................................ 2344
Create
........................................................................................................... 2345
Type
........................................................................................................... 2346
Arrow Objects
......................................................................................................................... 2347
CChartObjectArrow
................................................................................................................ 2348
Create
........................................................................................................... 2349
ArrowCode........................................................................................................... 2351
Anchor
........................................................................................................... 2353
Save
........................................................................................................... 2355
Load
........................................................................................................... 2356
Type
........................................................................................................... 2357
Arrows with
................................................................................................................
fixed code
2358
Create
........................................................................................................... 2360
ArrowCode........................................................................................................... 2362
Type
........................................................................................................... 2363
Control.........................................................................................................................
Objects
2364
CChartObjectText
................................................................................................................ 2365
Create
........................................................................................................... 2366
Angle
........................................................................................................... 2367
Font
........................................................................................................... 2368
FontSize ........................................................................................................... 2369
Anchor
........................................................................................................... 2370
Save
........................................................................................................... 2371
Load
........................................................................................................... 2372
Type
........................................................................................................... 2373
CChartObjectLabel
................................................................................................................ 2374
Create
........................................................................................................... 2375
X_Distance........................................................................................................... 2376
Y_Distance........................................................................................................... 2377
X_Size
........................................................................................................... 2378
Y_Size
........................................................................................................... 2379
Corner
........................................................................................................... 2380
Time
........................................................................................................... 2381
Price
........................................................................................................... 2382
Save
........................................................................................................... 2383
Load
........................................................................................................... 2384
Type
........................................................................................................... 2385
CChartObjectEdit
................................................................................................................ 2386
Create
........................................................................................................... 2387
TextAlign ........................................................................................................... 2388
X_Size
........................................................................................................... 2389
Y_Size
........................................................................................................... 2390
BackColor ........................................................................................................... 2391
BorderColor
........................................................................................................... 2392
ReadOnly ........................................................................................................... 2393
Angle
........................................................................................................... 2394
Save
........................................................................................................... 2395
Load
........................................................................................................... 2396
Type
........................................................................................................... 2397
CChartObjectButton
................................................................................................................ 2398
State
........................................................................................................... 2399
Save
........................................................................................................... 2400
Load
........................................................................................................... 2401
Type
........................................................................................................... 2402
CChartObjectSubChart
................................................................................................................ 2403
Create
........................................................................................................... 2405
X_Distance........................................................................................................... 2406
Y_Distance........................................................................................................... 2407
2000-2016, MetaQuotes Software Corp.
22
Content
Corner
........................................................................................................... 2408
X_Size
........................................................................................................... 2409
Y_Size
........................................................................................................... 2410
Symbol
........................................................................................................... 2411
Period
........................................................................................................... 2412
Scale
........................................................................................................... 2413
DateScale ........................................................................................................... 2414
PriceScale ........................................................................................................... 2415
Time
........................................................................................................... 2416
Price
........................................................................................................... 2417
Save
........................................................................................................... 2418
Load
........................................................................................................... 2419
Type
........................................................................................................... 2420
CChartObjectBitmap
................................................................................................................ 2421
Create
........................................................................................................... 2422
BmpFile ........................................................................................................... 2423
X_Offset ........................................................................................................... 2424
Y_Offset ........................................................................................................... 2425
Save
........................................................................................................... 2426
Load
........................................................................................................... 2427
Type
........................................................................................................... 2428
CChartObjectBmpLabel
................................................................................................................ 2429
Create
........................................................................................................... 2431
X_Distance........................................................................................................... 2432
Y_Distance........................................................................................................... 2433
X_Offset ........................................................................................................... 2434
Y_Offset ........................................................................................................... 2435
Corner
........................................................................................................... 2436
X_Size
........................................................................................................... 2437
Y_Size
........................................................................................................... 2438
BmpFileOn ........................................................................................................... 2439
BmpFileOff........................................................................................................... 2440
State
........................................................................................................... 2441
Time
........................................................................................................... 2442
Price
........................................................................................................... 2443
Save
........................................................................................................... 2444
Load
........................................................................................................... 2445
Type
........................................................................................................... 2446
CChartObjectRectLabel
................................................................................................................ 2447
Create
........................................................................................................... 2448
X_Size
........................................................................................................... 2449
Y_Size
........................................................................................................... 2450
BackColor ........................................................................................................... 2451
Angle
........................................................................................................... 2452
BorderType........................................................................................................... 2453
Save
........................................................................................................... 2454
Load
........................................................................................................... 2455
Type
........................................................................................................... 2456
............................................................................................................................2457
Class for creating
custom graphics
ChartObjectName
......................................................................................................................... 2460
Circle ......................................................................................................................... 2461
CircleAA......................................................................................................................... 2462
Create ......................................................................................................................... 2463
CreateBitmap
......................................................................................................................... 2464
CreateBitmapLabel
......................................................................................................................... 2466
Destroy......................................................................................................................... 2468
Erase ......................................................................................................................... 2469
Fill
......................................................................................................................... 2470
2000-2016, MetaQuotes Software Corp.
23
Content
FillCircle......................................................................................................................... 2471
FillRectangle
......................................................................................................................... 2472
FillTriangle
......................................................................................................................... 2473
FontAngleGet
......................................................................................................................... 2474
FontAngleSet
......................................................................................................................... 2475
FontFlagsGet
......................................................................................................................... 2476
FontFlagsSet
......................................................................................................................... 2477
FontGet......................................................................................................................... 2478
FontNameGet
......................................................................................................................... 2479
FontNameSet
......................................................................................................................... 2480
FontSet......................................................................................................................... 2481
FontSizeGet
......................................................................................................................... 2482
FontSizeSet
......................................................................................................................... 2483
Height ......................................................................................................................... 2484
Line ......................................................................................................................... 2485
LineAA ......................................................................................................................... 2486
LineHorizontal
......................................................................................................................... 2487
LineStyleSet
......................................................................................................................... 2488
LineVertical
......................................................................................................................... 2489
LoadFromFile
......................................................................................................................... 2490
PixelGet......................................................................................................................... 2491
PixelSet......................................................................................................................... 2492
PixelSetAA
......................................................................................................................... 2493
Polygon......................................................................................................................... 2494
PolygonAA
......................................................................................................................... 2495
Polyline......................................................................................................................... 2496
PolylineAA
......................................................................................................................... 2497
Rectangle
......................................................................................................................... 2498
Resize ......................................................................................................................... 2499
ResourceName
......................................................................................................................... 2500
TextHeight
......................................................................................................................... 2501
TextOut......................................................................................................................... 2502
TextSize
......................................................................................................................... 2503
TextWidth
......................................................................................................................... 2504
TransparentLevelSet
......................................................................................................................... 2505
Triangle......................................................................................................................... 2506
TriangleAA
......................................................................................................................... 2507
Update ......................................................................................................................... 2508
Width ......................................................................................................................... 2509
Class for w............................................................................................................................2510
orking w ith chart
ChartID......................................................................................................................... 2515
Mode ......................................................................................................................... 2516
Foreground
......................................................................................................................... 2517
Shift ......................................................................................................................... 2518
ShiftSize
......................................................................................................................... 2519
AutoScroll
......................................................................................................................... 2520
Scale ......................................................................................................................... 2521
ScaleFix......................................................................................................................... 2522
ScaleFix_11
......................................................................................................................... 2523
FixedMax
......................................................................................................................... 2524
FixedMin
......................................................................................................................... 2525
PointsPerBar
......................................................................................................................... 2526
ScalePPB
......................................................................................................................... 2527
ShowOHLC
......................................................................................................................... 2528
ShowLineBid
......................................................................................................................... 2529
ShowLineAsk
......................................................................................................................... 2530
ShowLastLine
......................................................................................................................... 2531
ShowPeriodSep
......................................................................................................................... 2532
2000-2016, MetaQuotes Software Corp.
24
Content
ShowGrid
......................................................................................................................... 2533
ShowVolumes
......................................................................................................................... 2534
ShowObjectDescr
......................................................................................................................... 2535
ShowDateScale
......................................................................................................................... 2536
ShowPriceScale
......................................................................................................................... 2537
ColorBackground
......................................................................................................................... 2538
ColorForeground
......................................................................................................................... 2539
ColorGrid
......................................................................................................................... 2540
ColorBarUp
......................................................................................................................... 2541
ColorBarDown
......................................................................................................................... 2542
ColorCandleBull
......................................................................................................................... 2543
ColorCandleBear
......................................................................................................................... 2544
ColorChartLine
......................................................................................................................... 2545
ColorVolumes
......................................................................................................................... 2546
ColorLineBid
......................................................................................................................... 2547
ColorLineAsk
......................................................................................................................... 2548
ColorLineLast
......................................................................................................................... 2549
ColorStopLevels
......................................................................................................................... 2550
VisibleBars
......................................................................................................................... 2551
WindowsTotal
......................................................................................................................... 2552
WindowIsVisible
......................................................................................................................... 2553
WindowHandle
......................................................................................................................... 2554
FirstVisibleBar
......................................................................................................................... 2555
WidthInBars
......................................................................................................................... 2556
WidthInPixels
......................................................................................................................... 2557
HeightInPixels
......................................................................................................................... 2558
PriceMin
......................................................................................................................... 2559
PriceMax
......................................................................................................................... 2560
Attach ......................................................................................................................... 2561
FirstChart
......................................................................................................................... 2562
NextChart
......................................................................................................................... 2563
Open ......................................................................................................................... 2564
Detach......................................................................................................................... 2565
Close ......................................................................................................................... 2566
BringToTop
......................................................................................................................... 2567
EventObjectCreate
......................................................................................................................... 2568
EventObjectDelete
......................................................................................................................... 2569
IndicatorAdd
......................................................................................................................... 2570
IndicatorDelete
......................................................................................................................... 2571
IndicatorsTotal
......................................................................................................................... 2572
IndicatorName
......................................................................................................................... 2573
Navigate
......................................................................................................................... 2574
Symbol ......................................................................................................................... 2575
Period ......................................................................................................................... 2576
Redraw......................................................................................................................... 2577
GetInteger
......................................................................................................................... 2578
SetInteger
......................................................................................................................... 2579
GetDouble
......................................................................................................................... 2580
SetDouble
......................................................................................................................... 2581
GetString
......................................................................................................................... 2582
SetString
......................................................................................................................... 2583
SetSymbolPeriod
......................................................................................................................... 2584
ApplyTemplate
......................................................................................................................... 2585
ScreenShot
......................................................................................................................... 2586
WindowOnDropped
......................................................................................................................... 2587
PriceOnDropped
......................................................................................................................... 2588
TimeOnDropped
......................................................................................................................... 2589
XOnDropped
......................................................................................................................... 2590
2000-2016, MetaQuotes Software Corp.
25
Content
YOnDropped
......................................................................................................................... 2591
Save ......................................................................................................................... 2592
Load ......................................................................................................................... 2593
Type ......................................................................................................................... 2594
Classes for............................................................................................................................2595
file operations
CFile ......................................................................................................................... 2596
Handle
................................................................................................................ 2598
Filename ................................................................................................................ 2599
Flags
................................................................................................................ 2600
SetUnicode................................................................................................................ 2601
SetCommon................................................................................................................ 2602
Open
................................................................................................................ 2603
Close
................................................................................................................ 2604
Delete
................................................................................................................ 2605
IsExist
................................................................................................................ 2606
Copy
................................................................................................................ 2607
Move
................................................................................................................ 2608
Size
................................................................................................................ 2609
Tell
................................................................................................................ 2610
Seek
................................................................................................................ 2611
Flush
................................................................................................................ 2612
IsEnding ................................................................................................................ 2613
IsLineEnding
................................................................................................................ 2614
FolderCreate
................................................................................................................ 2615
FolderDelete
................................................................................................................ 2616
FolderClean................................................................................................................ 2617
FileFindFirst
................................................................................................................ 2618
FileFindNext
................................................................................................................ 2619
FileFindClose
................................................................................................................ 2620
CFileBin......................................................................................................................... 2621
Open
................................................................................................................ 2623
WriteChar ................................................................................................................ 2624
WriteShort................................................................................................................ 2625
WriteInteger
................................................................................................................ 2626
WriteLong ................................................................................................................ 2627
WriteFloat................................................................................................................ 2628
WriteDouble
................................................................................................................ 2629
WriteString................................................................................................................ 2630
WriteCharArray
................................................................................................................ 2631
WriteShortArray
................................................................................................................ 2632
WriteIntegerArray
................................................................................................................ 2633
WriteLongArray
................................................................................................................ 2634
WriteFloatArray
................................................................................................................ 2635
WriteDoubleArray
................................................................................................................ 2636
WriteObject
................................................................................................................ 2637
ReadChar ................................................................................................................ 2638
ReadShort ................................................................................................................ 2639
ReadInteger
................................................................................................................ 2640
ReadLong ................................................................................................................ 2641
ReadFloat ................................................................................................................ 2642
ReadDouble................................................................................................................ 2643
ReadString................................................................................................................ 2644
ReadCharArray
................................................................................................................ 2645
ReadShortArray
................................................................................................................ 2646
ReadIntegerArray
................................................................................................................ 2647
ReadLongArray
................................................................................................................ 2648
ReadFloatArray
................................................................................................................ 2649
ReadDoubleArray
................................................................................................................ 2650
2000-2016, MetaQuotes Software Corp.
26
Content
ReadObject................................................................................................................ 2651
CFileTxt......................................................................................................................... 2652
Open
................................................................................................................ 2653
WriteString................................................................................................................ 2654
ReadString................................................................................................................ 2655
............................................................................................................................2656
Class for String
operations
CString......................................................................................................................... 2657
Str
................................................................................................................ 2659
Len
................................................................................................................ 2660
Copy
................................................................................................................ 2661
Fill
................................................................................................................ 2662
Assign
................................................................................................................ 2663
Append
................................................................................................................ 2664
Insert
................................................................................................................ 2665
Compare ................................................................................................................ 2666
CompareNoCase
................................................................................................................ 2667
Left
................................................................................................................ 2668
Right
................................................................................................................ 2669
Mid
................................................................................................................ 2670
Trim
................................................................................................................ 2671
TrimLeft ................................................................................................................ 2672
TrimRight ................................................................................................................ 2673
Clear
................................................................................................................ 2674
ToUpper ................................................................................................................ 2675
ToLower ................................................................................................................ 2676
Reverse ................................................................................................................ 2677
Find
................................................................................................................ 2678
FindRev ................................................................................................................ 2679
Remove ................................................................................................................ 2680
Replace ................................................................................................................ 2681
Classes for............................................................................................................................2682
w orking w ith Indicators
Base classes
......................................................................................................................... 2683
CSpreadBuffer
................................................................................................................ 2684
Size
........................................................................................................... 2685
SetSymbolPeriod
........................................................................................................... 2686
At
........................................................................................................... 2687
Refresh ........................................................................................................... 2688
RefreshCurrent
........................................................................................................... 2689
CTimeBuffer
................................................................................................................ 2690
Size
........................................................................................................... 2691
SetSymbolPeriod
........................................................................................................... 2692
At
........................................................................................................... 2693
Refresh ........................................................................................................... 2694
RefreshCurrent
........................................................................................................... 2695
CTickVolumeBuffer
................................................................................................................ 2696
Size
........................................................................................................... 2697
SetSymbolPeriod
........................................................................................................... 2698
At
........................................................................................................... 2699
Refresh ........................................................................................................... 2700
RefreshCurrent
........................................................................................................... 2701
CRealVolumeBuffer
................................................................................................................ 2702
Size
........................................................................................................... 2703
SetSymbolPeriod
........................................................................................................... 2704
At
........................................................................................................... 2705
Refresh ........................................................................................................... 2706
RefreshCurrent
........................................................................................................... 2707
CDoubleBuffer
................................................................................................................ 2708
Size
........................................................................................................... 2709
2000-2016, MetaQuotes Software Corp.
27
Content
SetSymbolPeriod
........................................................................................................... 2710
At
........................................................................................................... 2711
Refresh ........................................................................................................... 2712
RefreshCurrent
........................................................................................................... 2713
COpenBuffer
................................................................................................................ 2714
Refresh ........................................................................................................... 2715
RefreshCurrent
........................................................................................................... 2716
CHighBuffer
................................................................................................................ 2717
Refresh ........................................................................................................... 2718
RefreshCurrent
........................................................................................................... 2719
CLowBuffer................................................................................................................ 2720
Refresh ........................................................................................................... 2721
RefreshCurrent
........................................................................................................... 2722
CCloseBuffer
................................................................................................................ 2723
Refresh ........................................................................................................... 2724
RefreshCurrent
........................................................................................................... 2725
CIndicatorBuffer
................................................................................................................ 2726
Offset
........................................................................................................... 2727
Name
........................................................................................................... 2728
At
........................................................................................................... 2729
Refresh ........................................................................................................... 2730
RefreshCurrent
........................................................................................................... 2731
CSeries
................................................................................................................ 2732
Name
........................................................................................................... 2733
BuffersTotal
........................................................................................................... 2734
Timeframe ........................................................................................................... 2735
Symbol
........................................................................................................... 2736
Period
........................................................................................................... 2737
RefreshCurrent
........................................................................................................... 2738
BufferSize ........................................................................................................... 2739
BufferResize
........................................................................................................... 2740
Refresh ........................................................................................................... 2741
PeriodDescription
........................................................................................................... 2742
CPriceSeries
................................................................................................................ 2743
BufferResize
........................................................................................................... 2744
GetData ........................................................................................................... 2745
Refresh ........................................................................................................... 2746
MinIndex ........................................................................................................... 2747
MinValue ........................................................................................................... 2748
MaxIndex ........................................................................................................... 2749
MaxValue ........................................................................................................... 2750
CIndicator................................................................................................................ 2751
Handle
........................................................................................................... 2754
Status
........................................................................................................... 2755
FullRelease........................................................................................................... 2756
Create
........................................................................................................... 2757
BufferResize
........................................................................................................... 2758
BarsCalculated
........................................................................................................... 2759
GetData ........................................................................................................... 2760
Refresh ........................................................................................................... 2763
Minimum ........................................................................................................... 2764
MinValue ........................................................................................................... 2765
Maximum ........................................................................................................... 2766
MaxValue ........................................................................................................... 2767
MethodDescription
........................................................................................................... 2768
PriceDescription
........................................................................................................... 2769
VolumeDescription
........................................................................................................... 2770
AddToChart
........................................................................................................... 2771
2000-2016, MetaQuotes Software Corp.
28
Content
DeleteFromChart
........................................................................................................... 2772
CIndicators................................................................................................................ 2773
Create
........................................................................................................... 2774
Refresh ........................................................................................................... 2775
Timeseries
.........................................................................................................................
classes
2776
CiSpread ................................................................................................................ 2777
Create
........................................................................................................... 2778
BufferResize
........................................................................................................... 2779
GetData ........................................................................................................... 2780
Refresh ........................................................................................................... 2782
CiTime
................................................................................................................ 2783
Create
........................................................................................................... 2784
BufferResize
........................................................................................................... 2785
GetData ........................................................................................................... 2786
Refresh ........................................................................................................... 2788
CiTickVolume
................................................................................................................ 2789
Create
........................................................................................................... 2790
BufferResize
........................................................................................................... 2791
GetData ........................................................................................................... 2792
Refresh ........................................................................................................... 2794
CiRealVolume
................................................................................................................ 2795
Create
........................................................................................................... 2796
BufferResize
........................................................................................................... 2797
GetData ........................................................................................................... 2798
Refresh ........................................................................................................... 2800
CiOpen
................................................................................................................ 2801
Create
........................................................................................................... 2802
GetData ........................................................................................................... 2803
CiHigh
................................................................................................................ 2805
Create
........................................................................................................... 2806
GetData ........................................................................................................... 2807
CiLow
................................................................................................................ 2809
Create
........................................................................................................... 2810
GetData ........................................................................................................... 2811
CiClose
................................................................................................................ 2813
Create
........................................................................................................... 2814
GetData ........................................................................................................... 2815
Trend Indicators
......................................................................................................................... 2817
CiADX
................................................................................................................ 2818
MaPeriod ........................................................................................................... 2819
Create
........................................................................................................... 2820
Main
........................................................................................................... 2821
Plus
........................................................................................................... 2822
Minus
........................................................................................................... 2823
Type
........................................................................................................... 2824
CiADXWilder
................................................................................................................ 2825
MaPeriod ........................................................................................................... 2826
Create
........................................................................................................... 2827
Main
........................................................................................................... 2828
Plus
........................................................................................................... 2829
Minus
........................................................................................................... 2830
Type
........................................................................................................... 2831
CiBands ................................................................................................................ 2832
MaPeriod ........................................................................................................... 2833
MaShift ........................................................................................................... 2834
Deviation ........................................................................................................... 2835
Applied
........................................................................................................... 2836
Create
........................................................................................................... 2837
2000-2016, MetaQuotes Software Corp.
29
Content
Base
........................................................................................................... 2838
Upper
........................................................................................................... 2839
Lower
........................................................................................................... 2840
Type
........................................................................................................... 2841
CiEnvelopes................................................................................................................ 2842
MaPeriod ........................................................................................................... 2843
MaShift ........................................................................................................... 2844
MaMethod ........................................................................................................... 2845
Deviation ........................................................................................................... 2846
Applied
........................................................................................................... 2847
Create
........................................................................................................... 2848
Upper
........................................................................................................... 2849
Lower
........................................................................................................... 2850
Type
........................................................................................................... 2851
CiIchimoku................................................................................................................ 2852
TenkanSenPeriod
........................................................................................................... 2853
KijunSenPeriod
........................................................................................................... 2854
SenkouSpanBPeriod
........................................................................................................... 2855
Create
........................................................................................................... 2856
TenkanSen........................................................................................................... 2857
KijunSen ........................................................................................................... 2858
SenkouSpanA
........................................................................................................... 2859
SenkouSpanB
........................................................................................................... 2860
ChinkouSpan
........................................................................................................... 2861
Type
........................................................................................................... 2862
CiMA
................................................................................................................ 2863
MaPeriod ........................................................................................................... 2864
MaShift ........................................................................................................... 2865
MaMethod ........................................................................................................... 2866
Applied
........................................................................................................... 2867
Create
........................................................................................................... 2868
Main
........................................................................................................... 2869
Type
........................................................................................................... 2870
CiSAR
................................................................................................................ 2871
SarStep ........................................................................................................... 2872
Maximum ........................................................................................................... 2873
Create
........................................................................................................... 2874
Main
........................................................................................................... 2875
Type
........................................................................................................... 2876
CiStdDev ................................................................................................................ 2877
MaPeriod ........................................................................................................... 2878
MaShift ........................................................................................................... 2879
MaMethod ........................................................................................................... 2880
Applied
........................................................................................................... 2881
Create
........................................................................................................... 2882
Main
........................................................................................................... 2883
Type
........................................................................................................... 2884
CiDEMA ................................................................................................................ 2885
MaPeriod ........................................................................................................... 2886
IndShift ........................................................................................................... 2887
Applied
........................................................................................................... 2888
Create
........................................................................................................... 2889
Main
........................................................................................................... 2890
Type
........................................................................................................... 2891
CiTEMA
................................................................................................................ 2892
MaPeriod ........................................................................................................... 2893
IndShift ........................................................................................................... 2894
Applied
........................................................................................................... 2895
2000-2016, MetaQuotes Software Corp.
30
Content
Create
........................................................................................................... 2896
Main
........................................................................................................... 2897
Type
........................................................................................................... 2898
CiFrAMA ................................................................................................................ 2899
MaPeriod ........................................................................................................... 2900
IndShift ........................................................................................................... 2901
Applied
........................................................................................................... 2902
Create
........................................................................................................... 2903
Main
........................................................................................................... 2904
Type
........................................................................................................... 2905
CiAMA
................................................................................................................ 2906
MaPeriod ........................................................................................................... 2907
FastEmaPeriod
........................................................................................................... 2908
SlowEmaPeriod
........................................................................................................... 2909
IndShift ........................................................................................................... 2910
Applied
........................................................................................................... 2911
Create
........................................................................................................... 2912
Main
........................................................................................................... 2913
Type
........................................................................................................... 2914
CiVIDyA ................................................................................................................ 2915
CmoPeriod........................................................................................................... 2916
EmaPeriod ........................................................................................................... 2917
IndShift ........................................................................................................... 2918
Applied
........................................................................................................... 2919
Create
........................................................................................................... 2920
Main
........................................................................................................... 2921
Type
........................................................................................................... 2922
Oscillators
......................................................................................................................... 2923
CiATR
................................................................................................................ 2924
MaPeriod ........................................................................................................... 2925
Create
........................................................................................................... 2926
Main
........................................................................................................... 2927
Type
........................................................................................................... 2928
CiBearsPower
................................................................................................................ 2929
MaPeriod ........................................................................................................... 2930
Create
........................................................................................................... 2931
Main
........................................................................................................... 2932
Type
........................................................................................................... 2933
CiBullsPower
................................................................................................................ 2934
MaPeriod ........................................................................................................... 2935
Create
........................................................................................................... 2936
Main
........................................................................................................... 2937
Type
........................................................................................................... 2938
CiCCI
................................................................................................................ 2939
MaPeriod ........................................................................................................... 2940
Applied
........................................................................................................... 2941
Create
........................................................................................................... 2942
Main
........................................................................................................... 2943
Type
........................................................................................................... 2944
CiChaikin ................................................................................................................ 2945
FastMaPeriod
........................................................................................................... 2946
SlowMaPeriod
........................................................................................................... 2947
MaMethod ........................................................................................................... 2948
Applied
........................................................................................................... 2949
Create
........................................................................................................... 2950
Main
........................................................................................................... 2951
Type
........................................................................................................... 2952
CiDeMarker................................................................................................................ 2953
2000-2016, MetaQuotes Software Corp.
31
Content
MaPeriod ........................................................................................................... 2954
Create
........................................................................................................... 2955
Main
........................................................................................................... 2956
Type
........................................................................................................... 2957
CiForce ................................................................................................................ 2958
MaPeriod ........................................................................................................... 2959
MaMethod ........................................................................................................... 2960
Applied
........................................................................................................... 2961
Create
........................................................................................................... 2962
Main
........................................................................................................... 2963
Type
........................................................................................................... 2964
CiMACD ................................................................................................................ 2965
FastEmaPeriod
........................................................................................................... 2966
SlowEmaPeriod
........................................................................................................... 2967
SignalPeriod
........................................................................................................... 2968
Applied
........................................................................................................... 2969
Create
........................................................................................................... 2970
Main
........................................................................................................... 2971
Signal
........................................................................................................... 2972
Type
........................................................................................................... 2973
CiMomentum
................................................................................................................ 2974
MaPeriod ........................................................................................................... 2975
Applied
........................................................................................................... 2976
Create
........................................................................................................... 2977
Main
........................................................................................................... 2978
Type
........................................................................................................... 2979
CiOsMA ................................................................................................................ 2980
FastEmaPeriod
........................................................................................................... 2981
SlowEmaPeriod
........................................................................................................... 2982
SignalPeriod
........................................................................................................... 2983
Applied
........................................................................................................... 2984
Create
........................................................................................................... 2985
Main
........................................................................................................... 2986
Type
........................................................................................................... 2987
CiRSI
................................................................................................................ 2988
MaPeriod ........................................................................................................... 2989
Applied
........................................................................................................... 2990
Create
........................................................................................................... 2991
Main
........................................................................................................... 2992
Type
........................................................................................................... 2993
CiRVI
................................................................................................................ 2994
MaPeriod ........................................................................................................... 2995
Create
........................................................................................................... 2996
Main
........................................................................................................... 2997
Signal
........................................................................................................... 2998
Type
........................................................................................................... 2999
CiStochastic
................................................................................................................ 3000
Kperiod ........................................................................................................... 3001
Dperiod ........................................................................................................... 3002
Slowing
........................................................................................................... 3003
MaMethod ........................................................................................................... 3004
PriceField ........................................................................................................... 3005
Create
........................................................................................................... 3006
Main
........................................................................................................... 3007
Signal
........................................................................................................... 3008
Type
........................................................................................................... 3009
CiTriX
................................................................................................................ 3010
MaPeriod ........................................................................................................... 3011
2000-2016, MetaQuotes Software Corp.
32
Content
Applied
........................................................................................................... 3012
Create
........................................................................................................... 3013
Main
........................................................................................................... 3014
Type
........................................................................................................... 3015
CiWPR
................................................................................................................ 3016
CalcPeriod........................................................................................................... 3017
Create
........................................................................................................... 3018
Main
........................................................................................................... 3019
Type
........................................................................................................... 3020
Volume .........................................................................................................................
Indicators
3021
CiAD
................................................................................................................ 3022
Applied
........................................................................................................... 3023
Create
........................................................................................................... 3024
Main
........................................................................................................... 3025
Type
........................................................................................................... 3026
CiMFI
................................................................................................................ 3027
MaPeriod ........................................................................................................... 3028
Applied
........................................................................................................... 3029
Create
........................................................................................................... 3030
Main
........................................................................................................... 3031
Type
........................................................................................................... 3032
CiOBV
................................................................................................................ 3033
Applied
........................................................................................................... 3034
Create
........................................................................................................... 3035
Main
........................................................................................................... 3036
Type
........................................................................................................... 3037
CiVolumes ................................................................................................................ 3038
Applied
........................................................................................................... 3039
Create
........................................................................................................... 3040
Main
........................................................................................................... 3041
Type
........................................................................................................... 3042
Bill Williams
.........................................................................................................................
Indicators
3043
CiAC
................................................................................................................ 3044
Create
........................................................................................................... 3045
Main
........................................................................................................... 3046
Type
........................................................................................................... 3047
CiAlligator ................................................................................................................ 3048
JawPeriod ........................................................................................................... 3049
JawShift ........................................................................................................... 3050
TeethPeriod
........................................................................................................... 3051
TeethShift ........................................................................................................... 3052
LipsPeriod ........................................................................................................... 3053
LipsShift ........................................................................................................... 3054
MaMethod ........................................................................................................... 3055
Applied
........................................................................................................... 3056
Create
........................................................................................................... 3057
Jaw
........................................................................................................... 3058
Teeth
........................................................................................................... 3059
Lips
........................................................................................................... 3060
Type
........................................................................................................... 3061
CiAO
................................................................................................................ 3062
Create
........................................................................................................... 3063
Main
........................................................................................................... 3064
Type
........................................................................................................... 3065
CiFractals ................................................................................................................ 3066
Create
........................................................................................................... 3067
Upper
........................................................................................................... 3068
Lower
........................................................................................................... 3069
2000-2016, MetaQuotes Software Corp.
33
Content
Type
........................................................................................................... 3070
CiGator ................................................................................................................ 3071
JawPeriod ........................................................................................................... 3072
JawShift ........................................................................................................... 3073
TeethPeriod
........................................................................................................... 3074
TeethShift ........................................................................................................... 3075
LipsPeriod ........................................................................................................... 3076
LipsShift ........................................................................................................... 3077
MaMethod ........................................................................................................... 3078
Applied
........................................................................................................... 3079
Create
........................................................................................................... 3080
Upper
........................................................................................................... 3081
Lower
........................................................................................................... 3082
Type
........................................................................................................... 3083
CiBWMFI ................................................................................................................ 3084
Applied
........................................................................................................... 3085
Create
........................................................................................................... 3086
Main
........................................................................................................... 3087
Type
........................................................................................................... 3088
Custom.........................................................................................................................
indicators
3089
NumBuffers................................................................................................................ 3090
NumParams................................................................................................................ 3091
ParamType................................................................................................................ 3092
ParamLong................................................................................................................ 3093
ParamDouble
................................................................................................................ 3094
ParamString
................................................................................................................ 3095
Type
................................................................................................................ 3096
............................................................................................................................3097
Trade Classes
CAccountInfo
......................................................................................................................... 3098
Login
................................................................................................................ 3100
TradeMode................................................................................................................ 3101
TradeModeDescription
................................................................................................................ 3102
Leverage ................................................................................................................ 3103
StopoutMode
................................................................................................................ 3104
StopoutModeDescription
................................................................................................................ 3105
TradeAllowed
................................................................................................................ 3106
TradeExpert
................................................................................................................ 3107
LimitOrders
................................................................................................................ 3108
Balance ................................................................................................................ 3109
Credit
................................................................................................................ 3110
Profit
................................................................................................................ 3111
Equity
................................................................................................................ 3112
Margin
................................................................................................................ 3113
FreeMargin................................................................................................................ 3114
MarginLevel
................................................................................................................ 3115
MarginCall ................................................................................................................ 3116
MarginStopOut
................................................................................................................ 3117
Name
................................................................................................................ 3118
Server
................................................................................................................ 3119
Currency ................................................................................................................ 3120
Company ................................................................................................................ 3121
InfoInteger................................................................................................................ 3122
InfoDouble ................................................................................................................ 3123
InfoString ................................................................................................................ 3124
OrderProfitCheck
................................................................................................................ 3125
MarginCheck
................................................................................................................ 3126
FreeMarginCheck
................................................................................................................ 3127
MaxLotCheck
................................................................................................................ 3128
2000-2016, MetaQuotes Software Corp.
34
Content
MarginMode
................................................................................................................ 3129
MarginModeDescription
................................................................................................................ 3130
CSymbolInfo
......................................................................................................................... 3131
Refresh ................................................................................................................ 3135
RefreshRates
................................................................................................................ 3136
Name
................................................................................................................ 3137
Select
................................................................................................................ 3138
IsSynchronized
................................................................................................................ 3139
Volume
................................................................................................................ 3140
VolumeHigh................................................................................................................ 3141
VolumeLow................................................................................................................ 3142
Time
................................................................................................................ 3143
Spread
................................................................................................................ 3144
SpreadFloat................................................................................................................ 3145
TicksBookDepth
................................................................................................................ 3146
StopsLevel................................................................................................................ 3147
FreezeLevel
................................................................................................................ 3148
Bid
................................................................................................................ 3149
BidHigh ................................................................................................................ 3150
BidLow
................................................................................................................ 3151
Ask
................................................................................................................ 3152
AskHigh ................................................................................................................ 3153
AskLow
................................................................................................................ 3154
Last
................................................................................................................ 3155
LastHigh ................................................................................................................ 3156
LastLow ................................................................................................................ 3157
TradeCalcMode
................................................................................................................ 3158
TradeCalcModeDescription
................................................................................................................ 3159
TradeMode................................................................................................................ 3160
TradeModeDescription
................................................................................................................ 3161
TradeExecution
................................................................................................................ 3162
TradeExecutionDescription
................................................................................................................ 3163
SwapMode ................................................................................................................ 3164
SwapModeDescription
................................................................................................................ 3165
SwapRollover3days
................................................................................................................ 3166
SwapRollover3daysDescription
................................................................................................................ 3167
MarginInitial
................................................................................................................ 3168
MarginMaintenance
................................................................................................................ 3169
MarginLong................................................................................................................ 3170
MarginShort
................................................................................................................ 3171
MarginLimit................................................................................................................ 3172
MarginStop................................................................................................................ 3173
MarginStopLimit
................................................................................................................ 3174
TradeTimeFlags
................................................................................................................ 3175
TradeFillFlags
................................................................................................................ 3176
Digits
................................................................................................................ 3177
Point
................................................................................................................ 3178
TickValue ................................................................................................................ 3179
TickValueProfit
................................................................................................................ 3180
TickValueLoss
................................................................................................................ 3181
TickSize ................................................................................................................ 3182
ContractSize
................................................................................................................ 3183
LotsMin ................................................................................................................ 3184
LotsMax ................................................................................................................ 3185
LotsStep ................................................................................................................ 3186
LotsLimit ................................................................................................................ 3187
SwapLong ................................................................................................................ 3188
SwapShort ................................................................................................................ 3189
2000-2016, MetaQuotes Software Corp.
35
Content
CurrencyBase
................................................................................................................ 3190
CurrencyProfit
................................................................................................................ 3191
CurrencyMargin
................................................................................................................ 3192
Bank
................................................................................................................ 3193
Description................................................................................................................ 3194
Path
................................................................................................................ 3195
SessionDeals
................................................................................................................ 3196
SessionBuyOrders
................................................................................................................ 3197
SessionSellOrders
................................................................................................................ 3198
SessionTurnover
................................................................................................................ 3199
SessionInterest
................................................................................................................ 3200
SessionBuyOrdersVolume
................................................................................................................ 3201
SessionSellOrdersVolume
................................................................................................................ 3202
SessionOpen
................................................................................................................ 3203
SessionClose
................................................................................................................ 3204
SessionAW ................................................................................................................ 3205
SessionPriceSettlement
................................................................................................................ 3206
SessionPriceLimitMin
................................................................................................................ 3207
SessionPriceLimitMax
................................................................................................................ 3208
InfoInteger................................................................................................................ 3209
InfoDouble ................................................................................................................ 3210
InfoString ................................................................................................................ 3211
NormalizePrice
................................................................................................................ 3212
COrderInfo
......................................................................................................................... 3213
Ticket
................................................................................................................ 3215
TimeSetup ................................................................................................................ 3216
TimeSetupMsc
................................................................................................................ 3217
OrderType................................................................................................................ 3218
TypeDescription
................................................................................................................ 3219
State
................................................................................................................ 3220
StateDescription
................................................................................................................ 3221
TimeExpiration
................................................................................................................ 3222
TimeDone ................................................................................................................ 3223
TimeDoneMsc
................................................................................................................ 3224
TypeFilling ................................................................................................................ 3225
TypeFillingDescription
................................................................................................................ 3226
TypeTime ................................................................................................................ 3227
TypeTimeDescription
................................................................................................................ 3228
Magic
................................................................................................................ 3229
PositionId ................................................................................................................ 3230
VolumeInitial
................................................................................................................ 3231
VolumeCurrent
................................................................................................................ 3232
PriceOpen ................................................................................................................ 3233
StopLoss ................................................................................................................ 3234
TakeProfit ................................................................................................................ 3235
PriceCurrent
................................................................................................................ 3236
PriceStopLimit
................................................................................................................ 3237
Symbol
................................................................................................................ 3238
Comment ................................................................................................................ 3239
InfoInteger................................................................................................................ 3240
InfoDouble ................................................................................................................ 3241
InfoString ................................................................................................................ 3242
StoreState................................................................................................................ 3243
CheckState................................................................................................................ 3244
Select
................................................................................................................ 3245
SelectByIndex
................................................................................................................ 3246
CHistoryOrderInfo
......................................................................................................................... 3247
TimeSetup ................................................................................................................ 3249
2000-2016, MetaQuotes Software Corp.
36
Content
TimeSetupMsc
................................................................................................................ 3250
OrderType................................................................................................................ 3251
TypeDescription
................................................................................................................ 3252
State
................................................................................................................ 3253
StateDescription
................................................................................................................ 3254
TimeExpiration
................................................................................................................ 3255
TimeDone ................................................................................................................ 3256
TimeDoneMsc
................................................................................................................ 3257
TypeFilling ................................................................................................................ 3258
TypeFillingDescription
................................................................................................................ 3259
TypeTime ................................................................................................................ 3260
TypeTimeDescription
................................................................................................................ 3261
Magic
................................................................................................................ 3262
PositionId ................................................................................................................ 3263
VolumeInitial
................................................................................................................ 3264
VolumeCurrent
................................................................................................................ 3265
PriceOpen ................................................................................................................ 3266
StopLoss ................................................................................................................ 3267
TakeProfit ................................................................................................................ 3268
PriceCurrent
................................................................................................................ 3269
PriceStopLimit
................................................................................................................ 3270
Symbol
................................................................................................................ 3271
Comment ................................................................................................................ 3272
InfoInteger................................................................................................................ 3273
InfoDouble ................................................................................................................ 3274
InfoString ................................................................................................................ 3275
Ticket
................................................................................................................ 3276
SelectByIndex
................................................................................................................ 3277
CPositionInfo
......................................................................................................................... 3278
Time
................................................................................................................ 3280
TimeMsc ................................................................................................................ 3281
TimeUpdate................................................................................................................ 3282
TimeUpdateMsc
................................................................................................................ 3283
PositionType
................................................................................................................ 3284
TypeDescription
................................................................................................................ 3285
Magic
................................................................................................................ 3286
Identifier ................................................................................................................ 3287
Volume
................................................................................................................ 3288
PriceOpen ................................................................................................................ 3289
StopLoss ................................................................................................................ 3290
TakeProfit ................................................................................................................ 3291
PriceCurrent
................................................................................................................ 3292
Commission................................................................................................................ 3293
Swap
................................................................................................................ 3294
Profit
................................................................................................................ 3295
Symbol
................................................................................................................ 3296
Comment ................................................................................................................ 3297
InfoInteger................................................................................................................ 3298
InfoDouble ................................................................................................................ 3299
InfoString ................................................................................................................ 3300
Select
................................................................................................................ 3301
SelectByIndex
................................................................................................................ 3302
SelectByMagic
................................................................................................................ 3303
SelectByTicket
................................................................................................................ 3304
StoreState................................................................................................................ 3305
CheckState................................................................................................................ 3306
CDealInfo
......................................................................................................................... 3307
Order
................................................................................................................ 3309
2000-2016, MetaQuotes Software Corp.
37
Content
Time
................................................................................................................ 3310
TimeMsc ................................................................................................................ 3311
DealType ................................................................................................................ 3312
TypeDescription
................................................................................................................ 3313
Entry
................................................................................................................ 3314
EntryDescription
................................................................................................................ 3315
Magic
................................................................................................................ 3316
PositionId ................................................................................................................ 3317
Volume
................................................................................................................ 3318
Price
................................................................................................................ 3319
Commision ................................................................................................................ 3320
Swap
................................................................................................................ 3321
Profit
................................................................................................................ 3322
Symbol
................................................................................................................ 3323
Comment ................................................................................................................ 3324
InfoInteger................................................................................................................ 3325
InfoDouble ................................................................................................................ 3326
InfoString ................................................................................................................ 3327
Ticket
................................................................................................................ 3328
SelectByIndex
................................................................................................................ 3329
CTrade ......................................................................................................................... 3330
LogLevel ................................................................................................................ 3334
SetExpertMagicNumber
................................................................................................................ 3335
SetDeviationInPoints
................................................................................................................ 3336
SetTypeFilling
................................................................................................................ 3337
SetAsyncMode
................................................................................................................ 3338
SetMarginMode
................................................................................................................ 3339
OrderOpen................................................................................................................ 3340
OrderModify
................................................................................................................ 3342
OrderDelete
................................................................................................................ 3343
PositionOpen
................................................................................................................ 3344
PositionModify
................................................................................................................ 3345
PositionClose
................................................................................................................ 3346
PositionCloseBy
................................................................................................................ 3347
Buy
................................................................................................................ 3348
Sell
................................................................................................................ 3349
BuyLimit ................................................................................................................ 3350
BuyStop ................................................................................................................ 3351
SellLimit ................................................................................................................ 3352
SellStop ................................................................................................................ 3353
Request ................................................................................................................ 3354
RequestAction
................................................................................................................ 3355
RequestActionDescription
................................................................................................................ 3356
RequestMagic
................................................................................................................ 3357
RequestOrder
................................................................................................................ 3358
RequestSymbol
................................................................................................................ 3359
RequestVolume
................................................................................................................ 3360
RequestPrice
................................................................................................................ 3361
RequestStopLimit
................................................................................................................ 3362
RequestSL ................................................................................................................ 3363
RequestTP ................................................................................................................ 3364
RequestDeviation
................................................................................................................ 3365
RequestType
................................................................................................................ 3366
RequestTypeDescription
................................................................................................................ 3367
RequestTypeFilling
................................................................................................................ 3368
RequestTypeFillingDescription
................................................................................................................ 3369
RequestTypeTime
................................................................................................................ 3370
RequestTypeTimeDescription
................................................................................................................ 3371
2000-2016, MetaQuotes Software Corp.
38
Content
RequestExpiration
................................................................................................................ 3372
RequestComment
................................................................................................................ 3373
RequestPosition
................................................................................................................ 3374
RequestPositionBy
................................................................................................................ 3375
Result
................................................................................................................ 3376
ResultRetcode
................................................................................................................ 3377
ResultRetcodeDescription
................................................................................................................ 3378
ResultDeal ................................................................................................................ 3379
ResultOrder
................................................................................................................ 3380
ResultVolume
................................................................................................................ 3381
ResultPrice................................................................................................................ 3382
ResultBid ................................................................................................................ 3383
ResultAsk ................................................................................................................ 3384
ResultComment
................................................................................................................ 3385
CheckResult
................................................................................................................ 3386
CheckResultRetcode
................................................................................................................ 3387
CheckResultRetcodeDescription
................................................................................................................ 3388
CheckResultBalance
................................................................................................................ 3389
CheckResultEquity
................................................................................................................ 3390
CheckResultProfit
................................................................................................................ 3391
CheckResultMargin
................................................................................................................ 3392
CheckResultMarginFree
................................................................................................................ 3393
CheckResultMarginLevel
................................................................................................................ 3394
CheckResultComment
................................................................................................................ 3395
PrintRequest
................................................................................................................ 3396
PrintResult................................................................................................................ 3397
FormatRequest
................................................................................................................ 3398
FormatRequestResult
................................................................................................................ 3399
CTerminalInfo
......................................................................................................................... 3400
Build
................................................................................................................ 3402
IsConnected
................................................................................................................ 3403
IsDLLsAllowed
................................................................................................................ 3404
IsTradeAllowed
................................................................................................................ 3405
IsEmailEnabled
................................................................................................................ 3406
IsFtpEnabled
................................................................................................................ 3407
MaxBars ................................................................................................................ 3408
CodePage ................................................................................................................ 3409
CPUCores ................................................................................................................ 3410
MemoryPhysical
................................................................................................................ 3411
MemoryTotal
................................................................................................................ 3412
MemoryAvailable
................................................................................................................ 3413
MemoryUsed
................................................................................................................ 3414
IsX64
................................................................................................................ 3415
OpenCLSupport
................................................................................................................ 3416
DiskSpace ................................................................................................................ 3417
Language ................................................................................................................ 3418
Name
................................................................................................................ 3419
Company ................................................................................................................ 3420
Path
................................................................................................................ 3421
DataPath ................................................................................................................ 3422
CommonDataPath
................................................................................................................ 3423
InfoInteger................................................................................................................ 3424
InfoString ................................................................................................................ 3425
............................................................................................................................3426
Trading Strategy
Classes
Base classes
.........................................................................................................................
for Expert Advisors
3429
CExpertBase
................................................................................................................ 3430
InitPhase ........................................................................................................... 3432
TrendType........................................................................................................... 3433
2000-2016, MetaQuotes Software Corp.
39
Content
UsedSeries........................................................................................................... 3434
EveryTick ........................................................................................................... 3435
Open
........................................................................................................... 3436
High
........................................................................................................... 3437
Low
........................................................................................................... 3438
Close
........................................................................................................... 3439
Spread
........................................................................................................... 3440
Time
........................................................................................................... 3441
TickVolume........................................................................................................... 3442
RealVolume........................................................................................................... 3443
Init
........................................................................................................... 3444
Symbol
........................................................................................................... 3445
Period
........................................................................................................... 3446
Magic
........................................................................................................... 3447
ValidationSettings
........................................................................................................... 3448
SetPriceSeries
........................................................................................................... 3449
SetOtherSeries
........................................................................................................... 3450
InitIndicators
........................................................................................................... 3451
InitOpen ........................................................................................................... 3452
InitHigh ........................................................................................................... 3453
InitLow ........................................................................................................... 3454
InitClose ........................................................................................................... 3455
InitSpread ........................................................................................................... 3456
InitTime ........................................................................................................... 3457
InitTickVolume
........................................................................................................... 3458
InitRealVolume
........................................................................................................... 3459
PriceLevelUnit
........................................................................................................... 3460
StartIndex........................................................................................................... 3461
CompareMagic
........................................................................................................... 3462
CExpert ................................................................................................................ 3463
Init
........................................................................................................... 3467
Magic
........................................................................................................... 3468
InitSignal ........................................................................................................... 3469
InitTrailing........................................................................................................... 3470
InitMoney ........................................................................................................... 3471
InitTrade ........................................................................................................... 3472
Deinit
........................................................................................................... 3473
OnTickProcess
........................................................................................................... 3474
OnTradeProcess
........................................................................................................... 3475
OnTimerProcess
........................................................................................................... 3476
OnChartEventProcess
........................................................................................................... 3477
OnBookEventProcess
........................................................................................................... 3478
MaxOrders........................................................................................................... 3479
Signal
........................................................................................................... 3480
ValidationSettings
........................................................................................................... 3481
InitIndicators
........................................................................................................... 3482
OnTick
........................................................................................................... 3483
OnTrade ........................................................................................................... 3484
OnTimer ........................................................................................................... 3485
OnChartEvent
........................................................................................................... 3486
OnBookEvent
........................................................................................................... 3487
InitParameters
........................................................................................................... 3488
DeinitTrade
........................................................................................................... 3489
DeinitSignal
........................................................................................................... 3490
DeinitTrailing
........................................................................................................... 3491
DeinitMoney
........................................................................................................... 3492
DeinitIndicators
........................................................................................................... 3493
Refresh ........................................................................................................... 3494
2000-2016, MetaQuotes Software Corp.
40
Content
Processing........................................................................................................... 3495
CheckOpen........................................................................................................... 3497
CheckOpenLong
........................................................................................................... 3498
CheckOpenShort
........................................................................................................... 3499
OpenLong ........................................................................................................... 3500
OpenShort........................................................................................................... 3501
CheckReverse
........................................................................................................... 3502
CheckReverseLong
........................................................................................................... 3503
CheckReverseShort
........................................................................................................... 3504
ReverseLong
........................................................................................................... 3505
ReverseShort
........................................................................................................... 3507
CheckClose........................................................................................................... 3509
CheckCloseLong
........................................................................................................... 3510
CheckCloseShort
........................................................................................................... 3511
CloseAll ........................................................................................................... 3512
Close
........................................................................................................... 3513
CloseLong ........................................................................................................... 3514
CloseShort........................................................................................................... 3515
CheckTrailingStop
........................................................................................................... 3516
CheckTrailingStopLong
........................................................................................................... 3517
CheckTrailingStopShort
........................................................................................................... 3518
TrailingStopLong
........................................................................................................... 3519
TrailingStopShort
........................................................................................................... 3520
CheckTrailingOrderLong
........................................................................................................... 3521
CheckTrailingOrderShort
........................................................................................................... 3522
TrailingOrderLong
........................................................................................................... 3523
TrailingOrderShort
........................................................................................................... 3524
CheckDeleteOrderLong
........................................................................................................... 3525
CheckDeleteOrderShort
........................................................................................................... 3526
DeleteOrders
........................................................................................................... 3527
DeleteOrder
........................................................................................................... 3528
DeleteOrderLong
........................................................................................................... 3529
DeleteOrderShort
........................................................................................................... 3530
LotOpenLong
........................................................................................................... 3531
LotOpenShort
........................................................................................................... 3532
LotReverse........................................................................................................... 3533
PrepareHistoryDate
........................................................................................................... 3534
HistoryPoint
........................................................................................................... 3535
CheckTradeState
........................................................................................................... 3536
WaitEvent........................................................................................................... 3537
NoWaitEvent
........................................................................................................... 3538
TradeEventPositionStopTake
........................................................................................................... 3539
TradeEventOrderTriggered
........................................................................................................... 3540
TradeEventPositionOpened
........................................................................................................... 3541
TradeEventPositionVolumeChanged
........................................................................................................... 3542
TradeEventPositionModified
........................................................................................................... 3543
TradeEventPositionClosed
........................................................................................................... 3544
TradeEventOrderPlaced
........................................................................................................... 3545
TradeEventOrderModified
........................................................................................................... 3546
TradeEventOrderDeleted
........................................................................................................... 3547
TradeEventNotIdentified
........................................................................................................... 3548
TimeframeAdd
........................................................................................................... 3549
TimeframesFlags
........................................................................................................... 3550
SelectPosition
........................................................................................................... 3551
CExpertSignal
................................................................................................................ 3552
BasePrice ........................................................................................................... 3554
UsedSeries........................................................................................................... 3555
Weight
........................................................................................................... 3556
2000-2016, MetaQuotes Software Corp.
41
Content
PatternsUsage
........................................................................................................... 3557
General ........................................................................................................... 3558
Ignore
........................................................................................................... 3559
Invert
........................................................................................................... 3560
ThresholdOpen
........................................................................................................... 3561
ThresholdClose
........................................................................................................... 3562
PriceLevel........................................................................................................... 3563
StopLevel ........................................................................................................... 3564
TakeLevel ........................................................................................................... 3565
Expiration........................................................................................................... 3566
Magic
........................................................................................................... 3567
ValidationSettings
........................................................................................................... 3568
InitIndicators
........................................................................................................... 3569
AddFilter ........................................................................................................... 3570
CheckOpenLong
........................................................................................................... 3571
CheckOpenShort
........................................................................................................... 3572
OpenLongParams
........................................................................................................... 3573
OpenShortParams
........................................................................................................... 3574
CheckCloseLong
........................................................................................................... 3575
CheckCloseShort
........................................................................................................... 3576
CloseLongParams
........................................................................................................... 3577
CloseShortParams
........................................................................................................... 3578
CheckReverseLong
........................................................................................................... 3579
CheckReverseShort
........................................................................................................... 3580
CheckTrailingOrderLong
........................................................................................................... 3581
CheckTrailingOrderShort
........................................................................................................... 3582
LongCondition
........................................................................................................... 3583
ShortCondition
........................................................................................................... 3584
Direction ........................................................................................................... 3585
CExpertTrailing
................................................................................................................ 3586
CheckTrailingStopLong
........................................................................................................... 3587
CheckTrailingStopShort
........................................................................................................... 3588
CExpertMoney
................................................................................................................ 3589
Percent ........................................................................................................... 3590
ValidationSettings
........................................................................................................... 3591
CheckOpenLong
........................................................................................................... 3592
CheckOpenShort
........................................................................................................... 3593
CheckReverse
........................................................................................................... 3594
CheckClose........................................................................................................... 3595
Modules.........................................................................................................................
of Trade Signals
3596
Signals of the
................................................................................................................
Indicator Accelerator Oscillator
3599
Signals of the
................................................................................................................
Indicator Adaptive Moving Average
3602
Signals of the
................................................................................................................
Indicator Awesome Oscillator
3606
Signals of the
................................................................................................................
Oscillator Bears Power
3610
Signals of the
................................................................................................................
Oscillator Bulls Power
3612
Signals of the
................................................................................................................
Oscillator Commodity Channel Index
3614
Signals of the
................................................................................................................
Oscillator DeMarker
3618
Signals of the
................................................................................................................
Indicator Double Exponential Moving Average
3622
Signals of the
................................................................................................................
Indicator Envelopes
3626
Signals of the
................................................................................................................
Indicator Fractal Adaptive Moving Average
3629
Signals of the
................................................................................................................
Intraday Time Filter
3633
Signals of the
................................................................................................................
Oscillator MACD
3635
Signals of the
................................................................................................................
Indicator Moving Average
3641
Signals of the
................................................................................................................
Indicator Parabolic SAR
3645
Signals of the
................................................................................................................
Oscillator Relative Strength Index
3647
Signals of the
................................................................................................................
Oscillator Relative Vigor Index
3653
Signals of the
................................................................................................................
Oscillator Stochastic
3655
Signals of the
................................................................................................................
Oscillator Triple Exponential Average
3660
2000-2016, MetaQuotes Software Corp.
42
Content
Signals of the
................................................................................................................
Indicator Triple Exponential Moving Average
3664
Signals of the
................................................................................................................
Oscillator Williams Percent Range
3668
Trailing.........................................................................................................................
Stop Classes
3671
CTrailingFixedPips
................................................................................................................ 3672
StopLevel ........................................................................................................... 3673
ProfitLevel........................................................................................................... 3674
ValidationSettings
........................................................................................................... 3675
CheckTrailingStopLong
........................................................................................................... 3676
CheckTrailingStopShort
........................................................................................................... 3677
CTrailingMA................................................................................................................ 3678
Period
........................................................................................................... 3679
Shift
........................................................................................................... 3680
Method ........................................................................................................... 3681
Applied
........................................................................................................... 3682
InitIndicators
........................................................................................................... 3683
ValidationSettings
........................................................................................................... 3684
CheckTrailingStopLong
........................................................................................................... 3685
CheckTrailingStopShort
........................................................................................................... 3686
CTrailingNone
................................................................................................................ 3687
CheckTrailingStopLong
........................................................................................................... 3688
CheckTrailingStopShort
........................................................................................................... 3689
CTrailingPSAR
................................................................................................................ 3690
Step
........................................................................................................... 3691
Maximum ........................................................................................................... 3692
InitIndicators
........................................................................................................... 3693
CheckTrailingStopLong
........................................................................................................... 3694
CheckTrailingStopShort
........................................................................................................... 3695
Money Management
.........................................................................................................................
Classes
3696
CMoneyFixedLot
................................................................................................................ 3697
Lots
........................................................................................................... 3698
ValidationSettings
........................................................................................................... 3699
CheckOpenLong
........................................................................................................... 3700
CheckOpenShort
........................................................................................................... 3701
CMoneyFixedMargin
................................................................................................................ 3702
CheckOpenLong
........................................................................................................... 3703
CheckOpenShort
........................................................................................................... 3704
CMoneyFixedRisk
................................................................................................................ 3705
CheckOpenLong
........................................................................................................... 3706
CheckOpenShort
........................................................................................................... 3707
CMoneyNone
................................................................................................................ 3708
ValidationSettings
........................................................................................................... 3709
CheckOpenLong
........................................................................................................... 3710
CheckOpenShort
........................................................................................................... 3711
CMoneySizeOptimized
................................................................................................................ 3712
DecreaseFactor
........................................................................................................... 3713
ValidationSettings
........................................................................................................... 3714
CheckOpenLong
........................................................................................................... 3715
CheckOpenShort
........................................................................................................... 3716
Classes for............................................................................................................................3717
Control Panels and Dialogs
CRect ......................................................................................................................... 3719
Left
................................................................................................................ 3720
Top
................................................................................................................ 3721
Right
................................................................................................................ 3722
Bottom ................................................................................................................ 3723
Width
................................................................................................................ 3724
Height
................................................................................................................ 3725
SetBound ................................................................................................................ 3726
Move
................................................................................................................ 3727
2000-2016, MetaQuotes Software Corp.
43
Content
Shift
................................................................................................................ 3728
Contains ................................................................................................................ 3729
Format
................................................................................................................ 3730
CDateTime
......................................................................................................................... 3731
MonthName................................................................................................................ 3733
ShortMonthName
................................................................................................................ 3734
DayName ................................................................................................................ 3735
ShortDayName
................................................................................................................ 3736
DaysInMonth
................................................................................................................ 3737
DateTime ................................................................................................................ 3738
Date
................................................................................................................ 3739
Time
................................................................................................................ 3740
Sec
................................................................................................................ 3741
Min
................................................................................................................ 3742
Hour
................................................................................................................ 3743
Day
................................................................................................................ 3744
Mon
................................................................................................................ 3745
Year
................................................................................................................ 3746
SecDec
................................................................................................................ 3747
SecInc
................................................................................................................ 3748
MinDec
................................................................................................................ 3749
MinInc
................................................................................................................ 3750
HourDec ................................................................................................................ 3751
HourInc ................................................................................................................ 3752
DayDec ................................................................................................................ 3753
DayInc
................................................................................................................ 3754
MonDec ................................................................................................................ 3755
MonInc
................................................................................................................ 3756
YearDec ................................................................................................................ 3757
YearInc ................................................................................................................ 3758
CWnd ......................................................................................................................... 3759
Create
................................................................................................................ 3762
Destroy ................................................................................................................ 3763
OnEvent ................................................................................................................ 3764
OnMouseEvent
................................................................................................................ 3765
Name
................................................................................................................ 3766
ControlsTotal
................................................................................................................ 3767
Control ................................................................................................................ 3768
ControlFind................................................................................................................ 3769
Rect
................................................................................................................ 3770
Left
................................................................................................................ 3771
Top
................................................................................................................ 3772
Right
................................................................................................................ 3773
Bottom ................................................................................................................ 3774
Width
................................................................................................................ 3775
Height
................................................................................................................ 3776
Move
................................................................................................................ 3777
Shift
................................................................................................................ 3778
Resize
................................................................................................................ 3779
Contains ................................................................................................................ 3780
Alignment ................................................................................................................ 3781
Align
................................................................................................................ 3782
Id
................................................................................................................ 3783
IsEnabled ................................................................................................................ 3784
Enable
................................................................................................................ 3785
Disable
................................................................................................................ 3786
IsVisible ................................................................................................................ 3787
Visible
................................................................................................................ 3788
2000-2016, MetaQuotes Software Corp.
44
Content
Show
................................................................................................................ 3789
Hide
................................................................................................................ 3790
IsActive ................................................................................................................ 3791
Activate ................................................................................................................ 3792
Deactivate................................................................................................................ 3793
StateFlags ................................................................................................................ 3794
StateFlagsSet
................................................................................................................ 3795
StateFlagsReset
................................................................................................................ 3796
PropFlags ................................................................................................................ 3797
PropFlagsSet
................................................................................................................ 3798
PropFlagsReset
................................................................................................................ 3799
MouseX
................................................................................................................ 3800
MouseY
................................................................................................................ 3801
MouseFlags................................................................................................................ 3802
MouseFocusKill
................................................................................................................ 3803
OnCreate ................................................................................................................ 3804
OnDestroy ................................................................................................................ 3805
OnMove ................................................................................................................ 3806
OnResize ................................................................................................................ 3807
OnEnable ................................................................................................................ 3808
OnDisable ................................................................................................................ 3809
OnShow ................................................................................................................ 3810
OnHide
................................................................................................................ 3811
OnActivate................................................................................................................ 3812
OnDeactivate
................................................................................................................ 3813
OnClick ................................................................................................................ 3814
OnChange ................................................................................................................ 3815
OnMouseDown
................................................................................................................ 3816
OnMouseUp................................................................................................................ 3817
OnDragStart
................................................................................................................ 3818
OnDragProcess
................................................................................................................ 3819
OnDragEnd................................................................................................................ 3820
DragObjectCreate
................................................................................................................ 3821
DragObjectDestroy
................................................................................................................ 3822
CWndObj
......................................................................................................................... 3823
OnEvent ................................................................................................................ 3825
Text
................................................................................................................ 3826
Color
................................................................................................................ 3827
ColorBackground
................................................................................................................ 3828
ColorBorder
................................................................................................................ 3829
Font
................................................................................................................ 3830
FontSize ................................................................................................................ 3831
ZOrder
................................................................................................................ 3832
OnObjectCreate
................................................................................................................ 3833
OnObjectChange
................................................................................................................ 3834
OnObjectDelete
................................................................................................................ 3835
OnObjectDrag
................................................................................................................ 3836
OnSetText ................................................................................................................ 3837
OnSetColor................................................................................................................ 3838
OnSetColorBackground
................................................................................................................ 3839
OnSetFont ................................................................................................................ 3840
OnSetFontSize
................................................................................................................ 3841
OnSetZOrder
................................................................................................................ 3842
OnDestroy ................................................................................................................ 3843
OnChange ................................................................................................................ 3844
CWndContainer
......................................................................................................................... 3845
Destroy ................................................................................................................ 3847
OnEvent ................................................................................................................ 3848
2000-2016, MetaQuotes Software Corp.
45
Content
OnMouseEvent
................................................................................................................ 3849
ControlsTotal
................................................................................................................ 3850
Control ................................................................................................................ 3851
ControlFind................................................................................................................ 3852
Add
................................................................................................................ 3853
Delete
................................................................................................................ 3854
Move
................................................................................................................ 3855
Shift
................................................................................................................ 3856
Id
................................................................................................................ 3857
Enable
................................................................................................................ 3858
Disable
................................................................................................................ 3859
Show
................................................................................................................ 3860
Hide
................................................................................................................ 3861
MouseFocusKill
................................................................................................................ 3862
Save
................................................................................................................ 3863
Load
................................................................................................................ 3864
OnResize ................................................................................................................ 3865
OnActivate................................................................................................................ 3866
OnDeactivate
................................................................................................................ 3867
CLabel ......................................................................................................................... 3868
Create
................................................................................................................ 3869
OnSetText ................................................................................................................ 3870
OnSetColor................................................................................................................ 3871
OnSetFont ................................................................................................................ 3872
OnSetFontSize
................................................................................................................ 3873
OnCreate ................................................................................................................ 3874
OnShow ................................................................................................................ 3875
OnHide
................................................................................................................ 3876
OnMove ................................................................................................................ 3877
CBmpButton
......................................................................................................................... 3878
Create
................................................................................................................ 3880
Border
................................................................................................................ 3881
BmpNames ................................................................................................................ 3882
BmpOffName
................................................................................................................ 3883
BmpOnName
................................................................................................................ 3884
BmpPassiveName
................................................................................................................ 3885
BmpActiveName
................................................................................................................ 3886
Pressed ................................................................................................................ 3887
Locking ................................................................................................................ 3888
OnSetZOrder
................................................................................................................ 3889
OnCreate ................................................................................................................ 3890
OnShow ................................................................................................................ 3891
OnHide
................................................................................................................ 3892
OnMove ................................................................................................................ 3893
OnChange ................................................................................................................ 3894
OnActivate................................................................................................................ 3895
OnDeactivate
................................................................................................................ 3896
OnMouseDown
................................................................................................................ 3897
OnMouseUp................................................................................................................ 3898
CButton......................................................................................................................... 3899
Create
................................................................................................................ 3901
Pressed ................................................................................................................ 3902
Locking ................................................................................................................ 3903
OnSetText ................................................................................................................ 3904
OnSetColor................................................................................................................ 3905
OnSetColorBackground
................................................................................................................ 3906
OnSetColorBorder
................................................................................................................ 3907
OnSetFont ................................................................................................................ 3908
2000-2016, MetaQuotes Software Corp.
46
Content
OnSetFontSize
................................................................................................................ 3909
OnCreate ................................................................................................................ 3910
OnShow ................................................................................................................ 3911
OnHide
................................................................................................................ 3912
OnMove ................................................................................................................ 3913
OnResize ................................................................................................................ 3914
OnMouseDown
................................................................................................................ 3915
OnMouseUp................................................................................................................ 3916
CEdit ......................................................................................................................... 3917
Create
................................................................................................................ 3919
ReadOnly ................................................................................................................ 3920
TextAlign ................................................................................................................ 3921
OnObjectEndEdit
................................................................................................................ 3922
OnSetText ................................................................................................................ 3923
OnSetColor................................................................................................................ 3924
OnSetColorBackground
................................................................................................................ 3925
OnSetColorBorder
................................................................................................................ 3926
OnSetFont ................................................................................................................ 3927
OnSetFontSize
................................................................................................................ 3928
OnSetZOrder
................................................................................................................ 3929
OnCreate ................................................................................................................ 3930
OnShow ................................................................................................................ 3931
OnHide
................................................................................................................ 3932
OnMove ................................................................................................................ 3933
OnResize ................................................................................................................ 3934
OnChange ................................................................................................................ 3935
OnClick ................................................................................................................ 3936
CPanel ......................................................................................................................... 3937
Create
................................................................................................................ 3938
BorderType................................................................................................................ 3939
OnSetText ................................................................................................................ 3940
OnSetColorBackground
................................................................................................................ 3941
OnSetColorBorder
................................................................................................................ 3942
OnCreate ................................................................................................................ 3943
OnShow ................................................................................................................ 3944
OnHide
................................................................................................................ 3945
OnMove ................................................................................................................ 3946
OnResize ................................................................................................................ 3947
OnChange ................................................................................................................ 3948
CPicture
......................................................................................................................... 3949
Create
................................................................................................................ 3950
Border
................................................................................................................ 3951
BmpName ................................................................................................................ 3952
OnCreate ................................................................................................................ 3953
OnShow ................................................................................................................ 3954
OnHide
................................................................................................................ 3955
OnMove ................................................................................................................ 3956
OnChange ................................................................................................................ 3957
CScroll ......................................................................................................................... 3958
Create
................................................................................................................ 3960
OnEvent ................................................................................................................ 3961
MinPos
................................................................................................................ 3962
MaxPos
................................................................................................................ 3963
CurrPos ................................................................................................................ 3964
CreateBack................................................................................................................ 3965
CreateInc ................................................................................................................ 3966
CreateDec................................................................................................................ 3967
CreateThumb
................................................................................................................ 3968
2000-2016, MetaQuotes Software Corp.
47
Content
OnClickInc................................................................................................................ 3969
OnClickDec................................................................................................................ 3970
OnShow ................................................................................................................ 3971
OnHide
................................................................................................................ 3972
OnChangePos
................................................................................................................ 3973
OnThumbDragStart
................................................................................................................ 3974
OnThumbDragProcess
................................................................................................................ 3975
OnThumbDragEnd
................................................................................................................ 3976
CalcPos ................................................................................................................ 3977
CScrollV......................................................................................................................... 3978
CreateInc ................................................................................................................ 3979
CreateDec................................................................................................................ 3980
CreateThumb
................................................................................................................ 3981
OnResize ................................................................................................................ 3982
OnChangePos
................................................................................................................ 3983
OnThumbDragStart
................................................................................................................ 3984
OnThumbDragProcess
................................................................................................................ 3985
OnThumbDragEnd
................................................................................................................ 3986
CalcPos ................................................................................................................ 3987
CScrollH......................................................................................................................... 3988
CreateInc ................................................................................................................ 3989
CreateDec................................................................................................................ 3990
CreateThumb
................................................................................................................ 3991
OnResize ................................................................................................................ 3992
OnChangePos
................................................................................................................ 3993
OnThumbDragStart
................................................................................................................ 3994
OnThumbDragProcess
................................................................................................................ 3995
OnThumbDragEnd
................................................................................................................ 3996
CalcPos ................................................................................................................ 3997
CWndClient
......................................................................................................................... 3998
Create
................................................................................................................ 4000
OnEvent ................................................................................................................ 4001
ColorBackground
................................................................................................................ 4002
ColorBorder
................................................................................................................ 4003
BorderType................................................................................................................ 4004
VScrolled ................................................................................................................ 4005
HScrolled ................................................................................................................ 4006
CreateBack................................................................................................................ 4007
CreateScrollV
................................................................................................................ 4008
CreateScrollH
................................................................................................................ 4009
OnResize ................................................................................................................ 4010
OnVScrollShow
................................................................................................................ 4011
OnVScrollHide
................................................................................................................ 4012
OnHScrollShow
................................................................................................................ 4013
OnHScrollHide
................................................................................................................ 4014
OnScrollLineDown
................................................................................................................ 4015
OnScrollLineUp
................................................................................................................ 4016
OnScrollLineLeft
................................................................................................................ 4017
OnScrollLineRight
................................................................................................................ 4018
Rebound ................................................................................................................ 4019
CListView
......................................................................................................................... 4020
Create
................................................................................................................ 4022
OnEvent ................................................................................................................ 4023
TotalView ................................................................................................................ 4024
AddItem ................................................................................................................ 4025
Select
................................................................................................................ 4026
SelectByText
................................................................................................................ 4027
SelectByValue
................................................................................................................ 4028
2000-2016, MetaQuotes Software Corp.
48
Content
Value
................................................................................................................ 4029
CreateRow................................................................................................................ 4030
OnResize ................................................................................................................ 4031
OnVScrollShow
................................................................................................................ 4032
OnVScrollHide
................................................................................................................ 4033
OnScrollLineDown
................................................................................................................ 4034
OnScrollLineUp
................................................................................................................ 4035
OnItemClick
................................................................................................................ 4036
Redraw
................................................................................................................ 4037
RowState ................................................................................................................ 4038
CheckView................................................................................................................ 4039
CComboBox
......................................................................................................................... 4040
Create
................................................................................................................ 4042
OnEvent ................................................................................................................ 4043
AddItem ................................................................................................................ 4044
ListViewItems
................................................................................................................ 4045
Select
................................................................................................................ 4046
SelectByText
................................................................................................................ 4047
SelectByValue
................................................................................................................ 4048
Value
................................................................................................................ 4049
CreateEdit................................................................................................................ 4050
CreateButton
................................................................................................................ 4051
CreateList................................................................................................................ 4052
OnClickEdit................................................................................................................ 4053
OnClickButton
................................................................................................................ 4054
OnChangeList
................................................................................................................ 4055
ListShow ................................................................................................................ 4056
ListHide ................................................................................................................ 4057
CCheckBox
......................................................................................................................... 4058
Create
................................................................................................................ 4059
OnEvent ................................................................................................................ 4060
Text
................................................................................................................ 4061
Color
................................................................................................................ 4062
Checked ................................................................................................................ 4063
Value
................................................................................................................ 4064
CreateButton
................................................................................................................ 4065
CreateLabel
................................................................................................................ 4066
OnClickButton
................................................................................................................ 4067
OnClickLabel
................................................................................................................ 4068
CCheckGroup
......................................................................................................................... 4069
Create
................................................................................................................ 4071
OnEvent ................................................................................................................ 4072
AddItem ................................................................................................................ 4073
Value
................................................................................................................ 4074
CreateButton
................................................................................................................ 4075
OnVScrollShow
................................................................................................................ 4076
OnVScrollHide
................................................................................................................ 4077
OnScrollLineDown
................................................................................................................ 4078
OnScrollLineUp
................................................................................................................ 4079
OnChangeItem
................................................................................................................ 4080
Redraw
................................................................................................................ 4081
RowState ................................................................................................................ 4082
CRadioButton
......................................................................................................................... 4083
Create
................................................................................................................ 4084
OnEvent ................................................................................................................ 4085
Text
................................................................................................................ 4086
Color
................................................................................................................ 4087
State
................................................................................................................ 4088
2000-2016, MetaQuotes Software Corp.
49
Content
CreateButton
................................................................................................................ 4089
CreateLabel
................................................................................................................ 4090
OnClickButton
................................................................................................................ 4091
OnClickLabel
................................................................................................................ 4092
CRadioGroup
......................................................................................................................... 4093
Create
................................................................................................................ 4095
OnEvent ................................................................................................................ 4096
AddItem ................................................................................................................ 4097
Value
................................................................................................................ 4098
CreateButton
................................................................................................................ 4099
OnVScrollShow
................................................................................................................ 4100
OnVScrollHide
................................................................................................................ 4101
OnScrollLineDown
................................................................................................................ 4102
OnScrollLineUp
................................................................................................................ 4103
OnChangeItem
................................................................................................................ 4104
Redraw
................................................................................................................ 4105
RowState ................................................................................................................ 4106
Select
................................................................................................................ 4107
CSpinEdit
......................................................................................................................... 4108
Create
................................................................................................................ 4109
OnEvent ................................................................................................................ 4110
MinValue ................................................................................................................ 4111
MaxValue ................................................................................................................ 4112
Value
................................................................................................................ 4113
CreateEdit................................................................................................................ 4114
CreateInc ................................................................................................................ 4115
CreateDec................................................................................................................ 4116
OnClickInc................................................................................................................ 4117
OnClickDec................................................................................................................ 4118
OnChangeValue
................................................................................................................ 4119
CDialog......................................................................................................................... 4120
Create
................................................................................................................ 4122
OnEvent ................................................................................................................ 4123
Caption ................................................................................................................ 4124
Add
................................................................................................................ 4125
CreateWhiteBorder
................................................................................................................ 4126
CreateBackground
................................................................................................................ 4127
CreateCaption
................................................................................................................ 4128
CreateButtonClose
................................................................................................................ 4129
CreateClientArea
................................................................................................................ 4130
OnClickCaption
................................................................................................................ 4131
OnClickButtonClose
................................................................................................................ 4132
ClientAreaVisible
................................................................................................................ 4133
ClientAreaLeft
................................................................................................................ 4134
ClientAreaTop
................................................................................................................ 4135
ClientAreaRight
................................................................................................................ 4136
ClientAreaBottom
................................................................................................................ 4137
ClientAreaWidth
................................................................................................................ 4138
ClientAreaHeight
................................................................................................................ 4139
OnDialogDragStart
................................................................................................................ 4140
OnDialogDragProcess
................................................................................................................ 4141
OnDialogDragEnd
................................................................................................................ 4142
CAppDialog
......................................................................................................................... 4143
Create
................................................................................................................ 4145
Destroy ................................................................................................................ 4146
OnEvent ................................................................................................................ 4147
Run
................................................................................................................ 4148
ChartEvent................................................................................................................ 4149
2000-2016, MetaQuotes Software Corp.
50
Content
Minimized ................................................................................................................ 4150
IniFileSave ................................................................................................................ 4151
IniFileLoad................................................................................................................ 4152
IniFileName................................................................................................................ 4153
IniFileExt ................................................................................................................ 4154
CreateCommon
................................................................................................................ 4155
CreateExpert
................................................................................................................ 4156
CreateIndicator
................................................................................................................ 4157
CreateButtonMinMax
................................................................................................................ 4158
OnClickButtonClose
................................................................................................................ 4159
OnClickButtonMinMax
................................................................................................................ 4160
OnAnotherApplicationClose
................................................................................................................ 4161
Rebound ................................................................................................................ 4162
Minimize ................................................................................................................ 4163
Maximize ................................................................................................................ 4164
CreateInstanceId
................................................................................................................ 4165
ProgramName
................................................................................................................ 4166
SubwinOff ................................................................................................................ 4167
27
28
29
51
MQL5 Reference
MetaQuotes Language 5 (MQL5) is a high-level language designed for developing technical indicators,
trading robots and utility applications, which automate financial trading. MQL5 has been developed by
MetaQuotes Software Corp. for their trading platform. The language syntax is very close to C++
enabling programmers to develop applications in the object-oriented programming (OOP) style.
In addition to the MQL5 language, the trading platform package also includes the MetaEditor IDE with
highly advanced code writing tools, such as templates, snippets, debugging, profiling and auto
completion tools, as well as built-in MQL5 Storage enabling file versioning.
The language support is available on the MQL5.community website, which contains a huge free Code
Base and a plethora of articles. These articles cover all the aspects of the modern trading, including
neural networks, statistics and analysis, high-frequency trading, arbitrage, testing and optimization of
trading strategies, use of trading automation robots, and more.
Traders and MQL5 program developers can communicate on the forum, order and develop applications
using the Freelance service, as well as buy and sell protected programs in the Market of automated
trading applications.
The MQL5 language provides specialized trading functions and predefined event handlers to help
programmers develop Expert Advisors (EAs), which automatically control trading processes following
specific trading rules. In addition to EAs, MQL5 allows developing custom technical indicators, scripts
and libraries.
This MQL5 language reference contains functions, operations, reserved words and other language
constructions divided into categories. The reference also provides descriptions of Standard Library
classes used for developing trading strategies, control panels, custom graphics and enabling file
access.
Additionally, the Code Base contains the ALGLIB numerical analysis library, which can be used for
solving various mathematical problems.
handlers to manage predefined events which activate execution of appropriate trading strategy
elements. For example, an event of program initialization and deinitializtion, new ticks, timer
events, changes in the Depth of Market, chart and custom events.
In addition to calculating trading signals based on the implemented rules, Expert Advisors can also
automatically execute trades and send them directly to a trading server. Expert Advisors are stored
in <Terminal_Directory>\MQL5\Experts.
Custom Indicators is a technical indicator developed by a user in addition to standard indicators
integrated into the trading platform. Custom indicators, as well as standard ones, cannot trade
automatically, but only implement analytical functions. Custom indicators can utilize values of other
indicators for calculations, and can be called from Expert Advisors.
Custom indicators are stored in <Terminal_Directory>\MQL5\Indicators.
Script is a program for a single execution of an action. Unlike Expert Advisors, scripts do not handle
2000-2016, MetaQuotes Software Corp.
52
any event except for trigger, initialization and deinitialization. A script code must contain the
OnStart handler function.
Scripts are stored in <Terminal_DIrectory>\MQL5\Scripts.
Library is a set of custom functions. Libraries are intended to store and distribute commonly used
be included into the source texts of Expert Advisors, scripts, custom indicators, and libraries at the
compiling stage. The use of included files is more preferable than the use of libraries because of
additional burden occurring at calling library functions.
Include files can be stored in the same directory where the original file is located. In this case the
#include directive with double quotes is used. Another option is to store include files in
<Terminal_Directory>\MQL5\Include. In this case #include with angle brackets should be used.
53
Language Basics
Language Basics
The MetaQuotes Language 5 (MQL5) is an object-oriented high-level programming language intended
for writing automated trading strategies, custom technical indicators for the analysis of various
financial markets. It allows not only to write a variety of expert systems, designed to operate in real
time, but also create their own graphical tools to help you make trade decisions.
MQL5 is based on the concept of the popular programming language C++. As compared to MQL4, the
new language now has enumerations, structures, classes and event handling. By increasing the number
of embedded main types, the interaction of executable programs in MQL5 with other applications
through dll is now as easy as possible. MQL5 syntax is similar to the syntax of C++, and this makes it
easy to translate into it programs from modern programming languages.
To help you study the MQL5 language, all topics are grouped into the following sections:
Syntax
Data Types
Operations and Expressions
Operators
Functions
Variables
Preprocessor
Object-Oriented Programming
54
Language Basics
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;
no multiple inheritance.
See also
Enumerations, Structures and Classes, Inheritance
55
Language Basics
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:
//--- Single-line comment
/*
Multiline
comment
*/
56
Language Basics
Identifiers
Identifiers are used as names of variables and functions. The length of the identifier can not exceed
63 characters.
Characters allowed to be written in an identifier: figures 0-9, the Latin uppercase and lowercase
letters a-z and A-Z, recognized as different characters, the underscore character (_).The first
character can not be a digit.
The identifier must not coincide with reserved word.
Examples:
NAME1 namel Total_5 Paper
See also
Variables, Functions
57
Language Basics
Reserved Words
The following identifiers are recorded as reserved words, each of them corresponds to a certain
action, and cannot be used in another meaning:
Data Types
bool
enum
struct
char
float
uchar
class
int
uint
color
long
ulong
datetime
short
ushort
double
string
void
const
private
protected
public
virtual
Access Specificators
Memory Classes
extern
input
static
break
do
operator
case
else
return
continue
for
sizeof
default
if
switch
delete
new
while
false
#define
#property
this
#import
template
true
#include
typename
Operators
Other
58
Language Basics
59
Language Basics
Data Types
Any program operates with data. Data can be of different types depending on their purposes. For
example, integer data are used to access to array components. Price data belong to those of double
precision with floating point. This is related to the fact that no special data type for price data is
provided in MQL5.
Data of different types are processed with different rates. Integer data are processed at the fastest.
To process the double precision data, a special co-processor is used. However, because of complexity
of internal representation of data with floating point, they are processed slower than the integer ones.
String data are processed at the longest because of dynamic computer memory allocation/reallocation.
The basic data types are:
integers (char, short, int, long, uchar, ushort, uint, ulong);
logical (bool);
literals (ushort);
strings (string);
floating-point numbers (double, float);
color (color);
date and time (datetime);
enumerations (enum).
In terms of OOP complex data types are called abstract data types.
The color and datetime types make sense only to facilitate visualization and input of parameters
defined from outside - from the table of Expert Advisor or custom indicator properties (the Inputs
tab). Data of color and datetime types are represented as integers. Integer types and floating-point
types are called arithmetic (numeric) types.
Only implicit type casting is used in expressions, unless the explicit casting is specified.
See also
Typecasting
60
Language Basics
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 typecasting.
The table below lists the characteristics of each type. Besides, the last column features a type in C++
corresponding to each type.
Type
Size in Bytes
Minimum Value
Maximum Value
C++ Analog
char
-128
127
char
uchar
255
unsigned
BYTE
bool
0(false)
1(true)
bool
short
-32 768
32 767
short, wchar_t
ushort
65 535
unsigned
WORD
int
int
uint
unsigned
DWORD
color
-1
16 777 215
int, COLORREF
long
__int64
ulong
unsigned __int64
datetime
0
(1970.01.01
0:00:00)
__time64_t
char,
short,
int,
Integer type values can also be presented as numeric constants, color literals, date-time literals,
character constants and enumerations.
See also
Conversion Functions, Numerical Type Constants
61
Language Basics
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 signed one, and contains both
positive and negative values, the range of values is between -32 768 and 32 767.
ushort
The unsigned short type is the type ushort, which also has a size of 2 bytes. The minimum value is 0,
the maximum value is 65 535.
int
The size of the int type is 4 bytes (32 bits). The minimal value is -2 147 483 648, the maximal one is 2
147 483 647.
uint
The unsigned integer type is uint. It takes 4 bytes of memory and allows expressing integers from 0 to
4 294 967 295.
long
The size of the long type is 8 bytes (64 bits). The minimum value is -9 223 372 036 854 775 808, the
maximum value is 9 223 372 036 854 775 807.
ulong
The ulong type also occupies 8 bytes and can store values from 0 to 18 446 744 073 709 551 615.
Examples:
char
ch=12;
short sh=-5000;
int
in=2445777;
62
Language Basics
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:
//--- Infinite loop
void OnStart()
{
uchar
u_ch;
for(char ch=-128;ch<128;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_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:
ch= -128
u_ch= 128
ch= -127
u_ch= 129
ch= -126
u_ch= 130
ch= -125
u_ch= 131
ch= -124
u_ch= 132
ch= -123
u_ch= 133
ch= -122
u_ch= 134
ch= -121
u_ch= 135
ch= -120
u_ch= 136
ch= -119
u_ch= 137
ch= -118
u_ch= 138
ch= -117
u_ch= 139
ch= -116
u_ch= 140
ch= -115
u_ch= 141
ch= -114
u_ch= 142
ch= -113
u_ch= 143
ch= -112
u_ch= 144
ch= -111
u_ch= 145
63
Language Basics
...
Examples:
//--- Negative values can not be stored in unsigned types
uchar
u_ch=-120;
ushort u_sh=-5000;
uint
u_in=-401280;
Hexadecimal: numbers 0-9, the letters a-f or A-F for the values of 10-15; start with 0x or 0X.
Examples:
0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7
For integer variables, the values can be set in binary form using B prefix. For example, you can encode
the working hours of a trading session into int type variable and use information about them according
to the required algorithm:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- set 1 for working hours and 0 for nonworking ones
int AsianSession
//+------------------------------------------------------------------+
string GetHoursForSession(int session)
{
//--- in order to check, use AND bit operations and left shift by 1 bit <<=1
//--- start checking from the lowest bit
int bit=1;
string out="working hours: ";
//--- check all 24 bits starting from the zero and up to 23 inclusively
for(int i=0;i<24;i++)
{
//--- receive bit state in number
64
Language Basics
bool workinghour=(session&bit)==bit;
//--- add the hour's number to the message
if(workinghour )out=out+StringFormat("%d ",i);
//--- shift by one bit to the left to check the value of the next one
bit<<=1;
}
//--- result string
return out;
}
See also
Typecasting
65
Language Basics
Character Constants
Characters as elements of a string in MQL5 are indexes in the Unicode character set. They are
hexadecimal values that can be cast into integers, and that can be manipulated by integer operations
like addition and subtraction.
Any single character in quotation marks or a hexadecimal 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);
symbol_9 = 0x%x",symbol_0,symbol_9);
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:
Character name
Mnemonic code or
image
Record in MQL5
Numeric value
LF
'\n'
10
horizontal tab
HT
'\t'
carriage return
CR
'\r'
13
backslash
'\\'
92
single quote
'
'\''
39
double quote
"
'\"'
34
hexadecimal code
hhhh
'\xhhhh'
1 to 4 hexadecimal
characters
decimal code
'\d'
66
Language Basics
If a backslash is followed by a character other than those described above, result is undefined.
Example
void OnStart()
{
//--- declare character constants
int a='A';
int b='$';
int c='';
// code 0xA9
int d='\xAE';
As it was mentioned above, the value of a character constant (or variable) is an index in the table of
characters. Index being an integer, it can be written in different ways.
void OnStart()
{
67
Language Basics
//--int a=0xAE;
int b=0x24;
int c=0xA9;
int d=0x263A;
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()
68
Language Basics
Datetime Type
The datetime type is intended for storing the date and time as the number of seconds elapsed since
January 01, 1970. This type occupies 8 bytes of memory.
Constants of the date and time can be represented as a literal string, which consists of 6 parts
showing the numerical value of the year, month, day (or day, month, year), hours, minutes and
seconds. The constant is enclosed in single quotation marks and starts with the D character.
Values range from 1 January, 1970 to 31 December, 3000. Either date (year , month, day) or time
(hours, minutes, seconds), or all together can be omitted.
With literal date specification, it is desirable that you specify year, month and day. Otherwise the
compiler returns a warning about an incomplete entry.
Examples:
datetime NY=D'2015.01.01 00:00';
datetime d4=D'01.01.2004';
datetime compilation_date=__DATE__;
// Compilation date
datetime compilation_date_time=__DATETIME__;
datetime warning2=D'';
// Equal to __DATETIME__
See also
Structure of the Date Type, Date and Time, TimeToString, StringToTime
69
Language Basics
Color Type
The color type is intended for storing information about color and occupies 4 bytes in memory. The
first byte is ignored, the remaining 3 bytes contain the RGB-components.
Color constants can be represented in three ways: literally, by integers, or by name (for named Webcolors only).
Literal representation consists of three parts representing numerical rate values of the three main
color components: red, green, blue. The constant starts with C and is enclosed in single quotes.
Numerical rate values of a color component lie in the range from 0 to 255.
Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal
number looks like 0x00BBGGRR, where RR is the rate of the red color component, GG - of the green
one, and BB - of the blue one. Decimal constants are not directly reflected in the RGB. They represent
a decimal value of the hexadecimal integer representation.
Specific colors reflect the so-called Web-colors set.
Examples:
//--- Literals
C'128,128,128'
// Gray
C'0x00,0x00,0xFF' // Blue
//color names
clrRed
// Red
clrYellow
// Yellow
clrBlack
// Black
// White
16777215
// White
0x008000
// Green
32768
// Green
See also
Web Colors, ColorToString, StringToColor, Typecasting
70
Language Basics
Bool Type
The bool type is intended to store the logical values of true or false, numeric representation of them is
1 or 0, respectively.
Examples:
bool a = true;
bool b = false;
bool c = 1;
The internal representation is a whole number 1 byte large. It should be noted that in logical
expressions you can use other integer or real types or expressions of these types - the compiler will
not generate any error. In this case, the zero value will be interpreted as false, and all other values as true.
Examples:
int i=5;
double d=-2.5;
if(i) Print("i = ",i," and is set to true");
else Print("i = ",i," and is set to false");
if(d) Print("d = ",d," and has the true value");
else Print("d = ",d," and has the false value");
i=0;
if(i) Print("i = ",i," and has the true value");
else Print("i = ",i," and has the false value");
d=0.0;
if(d) Print("d = ",d," and has the true value");
else Print("d = ",d," and has the false value");
//--- Execution results
//
//
//
//
See also
Boolean Operations, Precedence Rules
71
Language Basics
Enumerations
Data of the enum type belong to a certain limited set of data. Defining the enumeration type:
enum name of enumerable type
{
list of values
};
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
After the enumeration is declared, a new integer-valued 4-byte data type appears. Declaration of the
new data type allows the compiler to strictly control types of passed parameters, because enumeration
introduces new named constants. In the above example, the January named constant has the value of
0, February - 1, December - 11.
Rule: If a certain value is not assigned to a named constant that is a member of the enumeration, its
new value will be formed automatically. If it is the first member of the enumeration, the 0 value will
be assigned to it. For all subsequent members, values will be calculated based on the value of the
previous members by adding one.
Example:
enum intervals
{
month=1,
two_months,
// Two months
quarter,
halfyear=6,
// Half a year
year=12,
// Year - 12 months
};
Notes
72
Language Basics
Unlike C++, the size of the internal representation of the enumerated type in MQL5 is always equal
73
Language Basics
Size in bytes
Minimal Positive
Value
Maximum Value
C++ Analog
float
1.175494351e-38
3.402823466e
+38
float
double
2.225073858507
2014e-308
1.797693134862
3158e+308
double
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.
74
Language Basics
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:
bool EqualDoubles(double d1,double d2,double epsilon)
{
if(epsilon<0) epsilon=-epsilon;
//--if(d1-d2>epsilon) return false;
if(d1-d2<-epsilon) return false;
//--return true;
}
void OnStart()
{
double d_val=0.7;
float
f_val=0.7;
f_val = ",DoubleToString(f_val,16));
f_val= 0.6999999880790710
Note that the value of epsilon in the above example can not be less than the predefined constant
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).
75
Language Basics
The second way offers comparing the normalized difference of two real numbers with zero. It's
meaningless to compare the difference of normalized numbers with a zero, because any mathematical
operation with normalized numbers gives a non-normalized result.
Example:
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double d_val=0.3;
float
f_val=0.3;
f_val = ",DoubleToString(f_val,16));
f_val= 0.3000000119209290
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:
double abnormal = MathArcsin(2.0);
Print("MathArcsin(2.0) =",abnormal);
// Result:
MathArcsin(2.0) = -1.#IND
Besides the minus infinity there is the plus infinity and NaN (not a number). To determine that this
number is invalid, you can use 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;
76
Language Basics
//--s1.d=MathArcsin(2.0);
s2=s1;
printf("1.
%f %I64X",s1.d,s2.l);
//--s2.l=0xFFFF000000000000;
s1=s2;
printf("2.
%f %I64X",s1.d,s2.l);
//--s2.l=0x7FF7000000000000;
s1=s2;
printf("3.
%f %I64X",s1.d,s2.l);
//--s2.l=0x7FF8000000000000;
s1=s2;
printf("4.
%f %I64X",s1.d,s2.l);
//--s2.l=0x7FFF000000000000;
s1=s2;
printf("5.
%f %I64X",s1.d,s2.l);
//--s2.l=0x7FF0000000000000;
s1=s2;
printf("6.
%f %I64X",s1.d,s2.l);
//--s2.l=0xFFF0000000000000;
s1=s2;
printf("7.
%f %I64X",s1.d,s2.l);
//--s2.l=0x8000000000000000;
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;
s1=s2;
printf("11.
%.16e %I64X",s1.d,s2.l);
//--s2.l=0x0010000000000000;
s1=s2;
printf("12.
%.16e %.16I64X",s1.d,s2.l);
//---
77
Language Basics
s1.d=0.7;
s2=s1;
printf("13.
%.16e %.16I64X",s1.d,s2.l);
/*
1.
-1.#IND00 FFF8000000000000
2.
-1.#QNAN0 FFFF000000000000
3.
1.#SNAN0 7FF7000000000000
4.
1.#QNAN0 7FF8000000000000
5.
1.#QNAN0 7FFF000000000000
6.
1.#INF00 7FF0000000000000
7.
-1.#INF00 FFF0000000000000
8.
-0.000000 8000000000000000
9.
0.500000 3FE0000000000000
10.
1.000000 3FF0000000000000
11.
1.7976931348623157e+308 7FEFFFFFFFFFFFFF
12.
2.2250738585072014e-308 0010000000000000
13.
6.9999999999999996e-001 3FE6666666666666
*/
See also
DoubleToString, NormalizeDouble, Numeric Type Constants
78
Language Basics
String Type
The string type is used for storing text strings. A text string is a sequence of characters in the
Unicode format with the final zero at the end of it. A string constant can be assigned to a string
variable. A string constant is a sequence of Unicode characters enclosed in double quotes: "This is a
string constant".
If you need to include a double quote (") into a string, the backslash character (\) must be put before
it. Any special character constants can be written in a string, if the backslash character (\) is typed
before them.
Examples:
string svar="This is a character string";
string svar2=StringSubstr(svar,0,4);
Print("Copyright symbol\t\x00A9");
FileWrite(handle,"This string contains a new line symbols \n");
string MT5path="C:\\Program Files\\MetaTrader 5";
To make the source code readable, long constant strings can be split into parts without addition
operation. During compilation, these parts will be combined into one long string:
//--- Declare a long constant string
string HTML_head="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
"<title>Trade Operations Report</title>\n"
"</head>";
//--- Output the constant string into log
Print(HTML_head);
}
See also
Conversion Functions, String Functions, FileOpen, FileReadString, FileWriteString
79
Language Basics
Structure Declaration
The structure data type is determined by the following description:
struct structure_name
{
elements_description
};
The structure name can't be used as an identifier (name of a variable or function). It should be noted
that in MQL5 structure elements follow one another directly, without alignment. In C++ such an order
is made to the compiler using the following instruction:
#pragma pack(1)
If you want to do another alignment in the structure, use auxiliary members, "fillers" to the right size.
Example:
struct trade_settings
{
uchar
slippage;
char
reserved1;
// skip 1 byte
short
reserved2;
// skip 2 bytes
int
reserved4;
double take;
double 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 uchar type.
In this case, the internal representation of data will always be the same regardless of the value
specified in #pragma pack().
If a structure contains variables of the string type and/or object of a dynamic array, the compiler
assigns an implicit constructor to such a structure. This constructor resets all the structure members
of string type and correctly initializes objects of the dynamic array.
Simple Structures
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
80
Language Basics
imported from DLL.
double stop;
uchar
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:
the keyword class is used in declaration;
by default, all class members have access specifier private, unless otherwise indicated. Data-
members of the structure have the default type of access as public, unless otherwise indicated;
class objects always have a table of virtual functions, even if there are no virtual functions declared
Classes and structures can have an explicit constructor and destructor. If your constructor is explicitly
defined, the initialization of a structure or class variable using the initializing sequence is impossible.
Example:
struct trade_settings
{
double take;
double stop;
uchar
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};
81
Language Basics
//+------------------------------------------------------------------+
class MyDateClass
{
private:
int
m_year;
// Year
int
m_month;
// Month
int
m_day;
int
m_hour;
// Hour in a day
int
m_minute;
// Minutes
int
m_second;
// Seconds
public:
//--- Default constructor
MyDateClass(void);
//--- Parametric constructor
MyDateClass(int h,int m,int s);
};
A constructor can be declared in the class description and then its body can be defined. For example,
two constructors of MyDateClass can be defined the following way:
//+------------------------------------------------------------------+
//| Default constructor
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(void)
{
//--MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;
82
Language Basics
m_hour=mdt.hour;
m_minute=mdt.min;
m_second=mdt.sec;
Print(__FUNCTION__);
}
//+------------------------------------------------------------------+
//| Parametric constructor
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(int h,int m,int s)
{
MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;
m_hour=h;
m_minute=m;
m_second=s;
Print(__FUNCTION__);
}
In the default constructor, all members of the class are filled using the TimeCurrent() function. In the
parametric constructor only hour values are filled in. Other members of the class (m_year, m_month
and m_day) will be automatically initialized with the current date.
The default constructor has a special purpose when initializing an array of objects of its class. The
constructor, all parameters of which have default values, is not a default constructor. Here is an
example:
//+------------------------------------------------------------------+
//| A class with a default constructor
//+------------------------------------------------------------------+
class CFoo
{
datetime
m_call_time;
public:
//--- Constructor with a parameter that has a default value is not a default constructor
CFoo(const datetime t=0){m_call_time=t;};
//--- Copy constructor
CFoo(const CFoo &foo){m_call_time=foo.m_call_time;};
string ToString(){return(TimeToString(m_call_time,TIME_DATE|TIME_SECONDS));};
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
// CFoo foo; // This variant cannot be used - a default constructor is not set
//--- Possible options to create the CFoo object
83
Language Basics
CFoo foo1(TimeCurrent());
CFoo foo2();
CFoo foo3=D'2009.09.09';
CFoo foo40(foo1);
CFoo foo41=foo1;
CFoo foo5;
// CFoo foo_array[3];
// You do not need to delete pfoo8 explicitly, since it points to the automatic
//delete pfoo9;
// You do not need to delete pfoo9 explicitly. since it points to the same obje
or
//CFoo foo_dyn_array[];
then the compiler will return an error for them "default constructor is not defined".
If a class has a user-defined constructor, the default constructor is not generated by the compiler. This
means that if a parametric constructor is declared in a class, but a default constructor is not declared,
you can not declare the arrays of objects of this class. The compiler will return an error for this script:
//+------------------------------------------------------------------+
//| A class without a default constructor
//+------------------------------------------------------------------+
class CFoo
{
string
m_name;
public:
84
Language Basics
CFoo(string name) { m_name=name;}
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get the "default constructor is not defined" error during compilation
CFoo badFoo[5];
}
In this example, the CFoo class has a declared parametric constructor - in such cases, the compiler
does not create a default constructor automatically during compilation. At the same time when you
declare an array of objects, it is assumed that all objects should be created and initialized
automatically. During auto-initialization of an object, it is necessary to call a default constructor, but
since the default constructor is not explicitly declared and not automatically generated by the compiler,
it is impossible to create such an object. For this reason, the compiler generates an error at the
compilation stage.
There is a special syntax to initialize an object using a constructor. Constructor initializers (special
constructions for initialization) for the members of a struct or class can be specified in the
initialization list.
An initialization list is a list of initializers separated by commas, which comes after the colon after
the list of parameters of a constructor and precedes the body (goes before an opening brace). There
are several requirements:
Initialization lists can be used only in constructors;
Parent members cannot be initialized in the initialization list;
The initialization list must be followed by a definition (implementation) of a function.
//+------------------------------------------------------------------+
class CPerson
{
string
m_first_name;
// First name
string
m_second_name;
// Second name
public:
//--- An empty default constructor
CPerson() {Print(__FUNCTION__);};
//--- A parametric constructor
CPerson(string full_name);
//--- A constructor with an initialization list
85
Language Basics
//+------------------------------------------------------------------+
CPerson::CPerson(string full_name)
{
int pos=StringFind(full_name," ");
if(pos>=0)
{
m_first_name=StringSubstr(full_name,0,pos);
m_second_name=StringSubstr(full_name,pos+1);
}
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get an error "default constructor is not defined"
CPerson people[5];
CPerson Tom="Tom Sawyer";
// Tom Sawyer
CPerson Huck("Huckleberry","Finn");
// Huckleberry Finn
an
initialization
list. Initializers
Note that the initialization using a list has replaced an assignment. Individual members must be
initialized as:
class_member (a list of expressions)
In the initialization list, members can go in any order, but all members of the class will be initialized
according to the order of their announcement. This means that in the third constructor, first the
m_first_name member will be initialized, as it is announced first, and only after it m_second_name is
initialized. This should be taken into account in cases where the initialization of some members of the
class depends on the values in other class members.
If a default constructor is not declared in the base class, and at the same time one or more
constructors with parameters are declared, you should always call one of the base class constructors in
the initialization list. It goes through the comma as ordinary members of the list and will be called first
86
Language Basics
during object initialization, no matter where in the initialization list it is located.
//+------------------------------------------------------------------+
//| Base class
//+------------------------------------------------------------------+
class CFoo
{
string
m_name;
public:
//--- A constructor with an initialization list
CFoo(string name) : m_name(name) { Print(m_name);}
};
//+------------------------------------------------------------------+
//| Class derived from CFoo
//+------------------------------------------------------------------+
class CBar : CFoo
{
CFoo
m_member;
public:
//--- A default constructor in the initialization list calls the constructor of a parent
CBar(): m_member(_Symbol), CFoo("CBAR") {Print(__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
CBar bar;
}
In this example, when creating the bar object, a default constructor CBar() will be called, in which first
a constructor for the parent CFoo is called, and then comes a constructor for the m_member class
member.
A destructor is a special function that is called automatically when a class object is destroyed. The
name of the destructor is written as a class name with a tilde (~). 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.
87
Language Basics
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
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()
virtual void
Draw()
{ return;
virtual bool
CheckDown(int& pad_array[]);
virtual bool
CheckLeft(int& side_row[]);
virtual bool
CheckRight(int& side_row[]);
};
Functions from SetRightBorder(int border) to Draw() are declared and defined directly inside the
CTetrisShape class.
The CTetrisShape() constructor and methods CheckDown(int& pad_array[]), CheckLeft(int&
side_row[]) and CheckRight(int& side_row[]) are only declared inside the class, but not defined yet.
Definitions of these functions will be further in the code. In order to define the method outside the
class, the scope resolution operator is used, the class name is used as the scope.
Example:
//+------------------------------------------------------------------+
//| Constructor of the basic class
//+------------------------------------------------------------------+
void CTetrisShape::CTetrisShape()
{
m_type=0;
m_ypos=0;
m_xpos=0;
m_xsize=SHAPE_SIZE;
m_ysize=SHAPE_SIZE;
m_prev_turn=0;
m_turn=0;
m_right_border=0;
88
Language Basics
}
//+------------------------------------------------------------------+
//| 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);
}
m_score;
// Score
int
m_ypos;
int
int
m_rows[FIELD_HEIGHT];
int
m_last_row;
CTetrisShape
bool
*m_shape;
m_bover;
// Tetris figure
// Game over
public:
void
void
Init();
void
Deinit();
void
Down();
void
Left();
void
Right();
void
Rotate();
void
Drop();
private:
void
NewShape();
void
CheckAndDeleteRows();
89
Language Basics
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
90
Language Basics
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:
double stat_array[5]; // 1-dimensional static array
some_function(stat_array);
...
bool some_function(double& array[])
{
if(ArrayResize(array,100)<0) return(false);
...
return(true);
}
Arrays in Structures
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 will be
created. Such an object is linked with the static array - member of structure.
See also
Array Functions, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and
Deleting Objects
91
Language Basics
Typecasting
Casting Numeric Types
Often a necessity occurs to convert one numeric type into another. Not all numeric types can be
converted into another. Here is the scheme of allowed casting:
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;
Print("n = ",n,"
f = ",f);
// result n= 123456789
f= 123456792.00000
A number converted into float has the same order, but is less accurate. Conversions, contrary to black
arrows, can be performed with possible data loss. Conversions between char and uchar, short and
ushort, int and uint, long and ulong (conversions to both sides), may lead to the loss of data.
As a result of converting floating point values to integer type, the fractional part is always deleted. If
you want to round off a float to the nearest whole number (which in many cases is more useful), you
should use MathRound().
Example:
//--- Gravitational acceleration
double g=9.8;
double round_g=(int)g;
double math_round_g=MathRound(g);
Print("round_g = ",round_g);
Print("math_round_g = ",math_round_g);
/*
Result:
round_g = 9
math_round_g = 10
*/
92
Language Basics
If two values are combined by a binary operator, before the operation execution the operand of a
lower type is converted to the higher type in accordance with the priority given in the below scheme:
The data types char, uchar, short, and ushort unconditionally are converted to the int type.
Examples:
char
c1=3;
c1/2+0.3 = 1.3
c1/2.0+0.3 = 1.8
The calculated expression consists of two operations. In the first example, the variable c1 of the char
type is converted to a temporary variable of the int type, because the second operand in the division
operation, the constant 2, is of the higher type int. As a result of the integer division 3/2 we get the
value 1, which is of the int type.
In the second operation of the first example, the second operand is the constant 0.3, which is of the
double type, so the result of the first operation is converted into a temporary variable of the double
type with a value of 1.0.
In the second example the variable of the char type c1 is converted to a temporary variable of the
double type, because the second operand in the division operation, the constant 2.0, is of the double
type; no further conversions are made.
An expression or function execution result can be used as the var_2 variable. The function style
notation of the explicit typecasting is also possible:
var_1 = type(var_2);
93
Language Basics
Print("(double)c1/2 + 0.3 = ",d2);
// Result:
(double)c1/2+0.3 = 1.80000000
Before the division operation is performed, the c1 variable is explicitly cast to the double type. Now
the integer constant 2 is cast to the value 2.0 of the double type, because as a result of converting the
first operand has taken the double type. In fact, the explicit typecasting is a unary operation.
Besides, when trying to cast types, the result may go beyond the permissible range. In this case, the
truncation occurs. For example:
char c;
uchar u;
c=400;
u=400;
Print("c = ",c); // Result c=-112
Print("u = ",u); // Result u=144
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:
int
i=1/2;
Print("i = 1/2
int k=1/2.0;
Print("k = 1/2
double d=1.0/2.0;
Print("e = 1/2.0; ",e);// that is the same as the target type, the result is 0.5
double x=1/2;
// the expression of the int type is cast to the double target typr,
When converting long/ulong type into double, precision may be lost in case the integer value is
greater than 9223372036854774784 or less than -9223372036854774784.
void OnStart()
{
long l_max=LONG_MAX;
long l_min=LONG_MIN+1;
//--- define the highest integer value, which does not lose accuracy when being cast to double
while(l_max!=long((double)l_max))
l_max--;
//--- define the lowest integer value, which does not lose accuracy when being cast to double
while(l_min!=long((double)l_min))
l_min++;
//--- derive the found interval for integer values
94
Language Basics
PrintFormat("When casting an integer value to double, it must be "
"within [%I64d, %I64d] interval",l_min,l_max);
//--- now, let's see what happens if the value falls out of this interval
PrintFormat("l_max+1=%I64d, double(l_max+1)=%.f, ulong(double(l_max+1))=%I64d",
l_max+1,double(l_max+1),long(double(l_max+1)));
PrintFormat("l_min-1=%I64d, double(l_min-1)=%.f, ulong(double(l_min-1))=%I64d",
l_min-1,double(l_min-1),long(double(l_min-1)));
//--- receive the following result
//
// string deinitialization
95
Language Basics
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);
s2=s1;
printf("1.
%f
%I64X",s1.d,s2.l);
//--s3=s2;
printf("2.
s3.high_part,s3.low_part);
//--s4.s="some constant string";
s3=s4;
printf("3.
buffer len is %d
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
96
Language Basics
a string.
#property script_show_inputs
input color
blue;
uchar
green;
uchar
red;
uchar
empty;
string
toString();
};
//--- 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());
//--}
97
Language Basics
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
98
Language Basics
Also NULL can be compared to pointers to objects created with the new operator.
See also
Variables, Functions
99
Language Basics
Object Pointers
In MQL5, there is a possibility to dynamically create objects of complex type. This is done by the new
operator, which returns a descriptor of the created object. Descriptor is 8 bytes large. Syntactically,
object descriptors in MQL5 are similar to pointers in C++.
Examples:
MyObject* hobject= new MyObject();
In contrast to C++, the hobject variable from example above is not a pointer to memory, but rather an
object descriptor. Furthermore, in MQL5 all objects in function parameters must be passed by
reference. Below are examples of passing objects as function parameters:
class Foo
{
public:
string
m_name;
int
m_id;
static int
s_counter;
Setup(string name)
{
m_name=name;
s_counter++;
m_id=s_counter;
}
};
int Foo::s_counter=0;
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare an object as variable with its automatic creation
Foo foo1;
//--- variant of passing an object by reference
PrintObject(foo1);
//--- declare a pointer to an object and create it using the 'new' operator
Foo *foo2=new Foo("foo2");
//--- variant of passing a pointer to an object by reference
PrintObject(foo2); // pointer to an object is converted automatically by compiler
//--- declare an array of objects of type Foo
Foo foo_objects[5];
100
Language Basics
//--- variant of passing an array of objects
PrintObjectsArray(foo_objects); // separate function for passing an array of objects
//--- declare an array of pointers to objects of type Foo
Foo *foo_pointers[5];
for(int i=0;i<5;i++)
{
foo_pointers[i]=new Foo("foo_pointer");
}
//--- variant of passing an array of pointers
PrintPointersArray(foo_pointers); // separate function for passing an array of pointers
//--- it is obligatory to delete objects created as pointers before termination
delete(foo2);
//--- delete array of pointers
int size=ArraySize(foo_pointers);
for(int i=0;i<5;i++)
delete(foo_pointers[i]);
//--}
//+------------------------------------------------------------------+
//| Objects are always passed by reference
//+------------------------------------------------------------------+
void PrintObject(Foo &object)
{
Print(__FUNCTION__,": ",object.m_id," Object name=",object.m_name);
}
//+------------------------------------------------------------------+
//| Passing an array of objects
//+------------------------------------------------------------------+
void PrintObjectsArray(Foo &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}
//+------------------------------------------------------------------+
//| Passing an array of pointers to object
//+------------------------------------------------------------------+
void PrintPointersArray(Foo* &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}
101
Language Basics
//+------------------------------------------------------------------+
See also
Variables, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and
Deleting Objects
102
Language Basics
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,
103
Language Basics
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
CDemoClass
setArray(double &array[]);
*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, GetPointer(this)
can't be used.
See also
Object Pointers, Creating and Deleting Objects, Visibility Scope and Lifetime of Variables
104
Language Basics
&& ||
= += *=
Operation symbols are used in expressions and have sense when appropriate operands are given to
them. Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and
semicolon.
Operation symbols, punctuation marks, and spaces are used to separate language elements from each
other.
This section contains the description of the following topics:
Expressions
Arithmetic Operations
Assignment Operations
Operations of Relation
Boolean Operations
Bitwise Operations
Other Operations
Priorities and Operations Order
105
Language Basics
Expressions
An expression consists of one or more operands and operation symbols. An expression can be written
in several lines.
Examples:
a++; b = 10;
//---
x = (y * z) /
(w + 2) + 127;
106
Language Basics
Arithmetic Operations
Arithmetic operations include additive and multiplicative operations:
Sum of variables
i = j + 2;
Difference of variables
i = j - 3;
x = - x;
Product of variables
z = 3 * x;
Division quotient
i = j / 5;
Remainder of division
i++;
++i;
k--;
--k;
Increment and decrement operations are applied only to variables, they can't be applied to constants.
The prefix increment (++i) and decrement (--k) are applied to the variable right before this variable is
used in an expression.
Post-increment (i++) and post-decrement (k--) are applied to the variable right after this variable is
used in an expression.
Important Notice
int i=5;
int k = i++ + ++i;
Computational problems may occur while moving the above expression from one programming
environment to another one (for example, from Borland C++ to MQL5). In general, the order of
computations depends on the compiler implementation. In practice, there are two ways to implement
the post-decrement (post-increment):
1. The post-decrement (post-increment) is applied to the variable after calculating the whole
expression.
2. The post-decrement (post-increment) is applied to the variable immediately at the operation.
Currently the first way of post-decrement (post-increment) calculation is implemented in MQL5. But
even knowing this peculiarity, it is not recommended to experiment with its use.
Examples:
int a=3;
a++;
// valid expression
int b=(a++)*3;
// invalid expression
See also
Precedence Rules
107
Language Basics
Assignment Operations
The value of the expression that includes the given operation is the value of the left operand after
assignment:
Assigning the value of x to the y variable
y = x;
The following operations unite arithmetic or bitwise operations with operation of assignment:
Adding x to the y variable
y += x;
y -= x;
y *= x;
y /= x;
y %= x;
y >>= x;
y <<= x;
y &= x;
y |= x;
y ^= x;
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
108
Language Basics
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;
a != b;
a < b;
a > b;
a <= b;
a >= b;
The equality of two real numbers can't be compared. In most cases, two seemingly identical numbers
can be unequal because of different values in the 15th decimal place. In order to correctly compare two
real numbers, compare the normalized difference of these numbers with zero.
Example:
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double first=0.3;
double second=3.0;
double third=second-2.7;
if(first!=third)
{
if(CompareDoubles(first,third))
printf("%.16f and %.16f are equal",first,third);
}
}
// Result: 0.3000000000000000
0.2999999999999998
are equal
See also
Precedence Rules
109
Language Basics
Boolean Operations
Logical Negation NOT (!)
Operand of the logical negation (!) must be of arithmetic type. The result is TRUE (1), if the operand
value is FALSE (0); and it is equal to FALSE (0), if the operand differs from FALSE (0).
if(!a) Print("not 'a'");
//+------------------------------------------------------------------+
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");
}
}
//+------------------------------------------------------------------+
110
Language Basics
//| the function always returns false
//+------------------------------------------------------------------+
bool func_false()
{
Print("Function func_false()");
return(false);
}
//+------------------------------------------------------------------+
//| the function always returns true
//+------------------------------------------------------------------+
bool func_true()
{
Print("Function func_true()");
return(true);
}
See also
Precedence Rules
111
Language Basics
Bitwise Operations
Complement to One
Complement of the variable value up to one. The value of the expression contains 1 in all digits where
the variable value contains 0, and 0 in all digits where the variable contains 1.
b = ~n;
Example:
char a='a',b;
b=~a;
Print("a = ",a, "
b = ",b);
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);
a = ",a, "
b = ",b);
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);
a = ",a, "
b = ",b);
112
Language Basics
// The result will be:
// Before:
a = 97
b = 98
// After:
a = 97
b = -62
It is not recommended to shift by the number of bits larger or equal to the length of the variable
shifted, because the result of such an operation is undefined.
Example:
char a='a',b='b';
//--- AND operation
char c=a&b;
Print("a = ",a,"
b = ",b);
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
Example:
113
Language Basics
char a='a', b='b';
//--- Excluding OR operation
char c=a^b;
Print("a = ",a,"
b = ",b);
Print("a ^ b = ",c);
// The result will be:
// a = 97
b = 98
// a ^ b = 3
114
Language Basics
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:
array[i] = 3; // Assign the value of 3 to i-th element of the array.
Only an integer can be index of an array. Four-dimensional and below arrays are allowed. Each
dimension is indexed from 0 to dimension size-1. In particular case, for a one-dimensional array
consisting of 50 elements, the reference to the first element will look like array [0], that to the last
element will be array [49].
When addressing beyond the array, the executing subsystem will generate a critical error, and the
program will be stopped.
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:
115
Language Basics
for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);
Dot Operator ( . )
For the direct access to the public members of structures and classes the dot operation is used.
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;
If there is no scope name, this is the explicit direction to use the global scope. If there is no scope
resolution operation, the function is sought in the nearest scope. If there is no function in the local
scope, the search is conducted in the global scope.
The scope resolution operation is also used to define function-class member.
type Class_name::Function_name(parameters_description)
{
// function body
}
Use of several functions of the same name from different execution contexts in a program may cause
ambiguity. The priority order of function calls without explicit scope specification is the following:
1. Class methods. If no function with the specified name is set in the class, move to the next level.
2. MQL5 functions. If the language does not have such a function, move to the next level.
3. User defined global functions. If no function with the specified name is found, move to the next
level.
116
Language Basics
4. Imported functions. If no function with the specified name is found, the compiler returns an error.
To avoid the ambiguity of function calls, always explicitly specify the function scope using the scope
resolution operation.
Example:
#property script_show_inputs
#import "kernel32.dll"
int GetLastError(void);
#import
class CCheckContext
{
int
m_id;
public:
CCheckContext() { m_id=1234; }
protected:
int
GetLastError() { return(m_id); }
};
class CCheckContext2 : public CCheckContext
{
int
m_id2;
public:
CCheckContext2() { m_id2=5678; }
void
Print();
protected:
int
GetLastError() { return(m_id2); }
};
void CCheckContext2::Print()
{
::Print("Terminal GetLastError",::GetLastError());
::Print("kernel32 GetLastError",kernel32::GetLastError());
::Print("parent GetLastError",CCheckContext::GetLastError());
::Print("our GetLastError",GetLastError());
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--CCheckContext2 test;
test.Print();
}
//+------------------------------------------------------------------+
117
Language Basics
Object ( sizeof )
Using the sizeof operation, the memory size corresponding to an identifier or type can be defined. The
sizeof operation is of the following format:
Example:
sizeof(expression)
Any identifier, or type name enclosed in brackets can be used as an expression. Note that the void
type name can't be used, and the identifier cannot belong to the field of bits, or be a function name.
If the expression is the name of a static array (i.e. the first dimension is given), then the result is the
size of the whole array (i.e. the product of the number of elements and the length of the type). If the
expression is the name of a dynamic array (the first dimension is not specified), the result will be the
size of the object of the dynamic array.
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));
118
Language Basics
Precedence Rules
Each group of operations in the table has the same priority. The higher the priority of operations is,
the higher it is position of the group in the table. The precedence rules determine the grouping of
operations and operands.
Attention: Precedence of operations in the MQL5 language corresponds to the priority adopted in C++,
and differs from the priority given in the MQL4 language.
Operation
Desciption
Execution Order
()
[]
.
Function Call
Referencing to an array
element
Referencing to a structure
element
!
~
++
-(type)
sizeof
Logical negation
Bitwise negation (complement)
Sign changing
Increment by one
Decrement by one
Typecasting
Determining size in bytes
Right to left
*
/
%
Multiplication
Division
Module division
Addition
Subtraction
<<
>>
Left shift
Right shift
<
<=
>
>=
Less than
Less than or equal
Greater than
Greater than or equal
==
!=
Equal
Not equal
&
Bitwise exclusive OR
Bitwise OR operation
&&
||
Logical OR operation
?:
Conditional Operator
Right to left
=
*=
Assignment
Multiplication with assignment
Right to left
119
Language Basics
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
Comma
To change the operation execution order, parenthesis that are of higher priority are used.
120
Language Basics
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
Compound operator {}
return operator
?: conditional operator
break operator
continue operator
new operator
delete operator
which
One operator can occupy one or more lines. Two or more operators can be located in the same line.
Operators that control over the execution order (if, if-else, switch, while and for), can be nested into
each other.
Example:
if(Month() == 12)
121
Language Basics
if(Day() == 31) Print("Happy New Year!");
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
122
Language Basics
Compound Operator
A compound operator (a block) consists of one or more operators of any type, enclosed in braces {}.
The closing brace must not be followed by a semicolon (;).
Example:
if(x==0)
{
Print("invalid position x = ",x);
return;
}
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
123
Language Basics
Expression Operator
Any expression followed by a semicolon (;) is the operator. Here are some examples of expression
operators.
Assignment Operator
Identifier = expression;
x=3;
y=x=3;
bool equal=(x==y);
Assignment operator can be used many times in an expression. In this case, the expression is
processed from left to right:
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
124
Language Basics
Return Operator
The return operator terminates the current function execution and returns control to the calling
program. The expression calculation result is returned to the calling function. The expression can
contain an assignment operator.
Example:
int CalcSum(int x, int y)
{
return(x+y);
}
In functions with the void return type, the return operator without expression must be used:
void SomeFunction()
{
Print("Hello!");
return;
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
125
Language Basics
If the expression is true, operator1 is executed and control is given to the operator that follows
operator2 (operator2 is not executed). If the expression is false, operator2 is executed.
The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators
with omitted else part. In this case, else addresses to the nearest previous if operator in the same
block that has no else part.
Examples:
//--- The else part refers to the second if operator:
if(x>1)
if(y==2) z=5;
else
z=6;
z=6;
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
126
Language Basics
Ternary Operator ?:
The general form of the ternary operator is as follows:
expression1 ? expression2 : expression3
For the first operand - "expression1" - any expression that results in a bool type value can be used. If
the result is true, then the operator set by the second operand, i.e. "expression2" is executed.
If the first operand is false, the third operand - "expression3" is performed. The second and third
operands, i.e. "expression2" and "expression3" should return values of one type and should not be of
void type. The result of the conditional operator execution is the result of expression2 or result of the
expression3, depending on the result of expression1.
//--- normalize difference between open and close prices for a day range
double true_range = (High==Low)?0:(Close-Open)/(High-Low);
127
Language Basics
void func(double d) { Print("double argument: ",d); }
void func(string s) { Print("string argument: ",s); }
bool
Expression1=true;
double Expression2=M_PI;
string Expression3="3.1415926";
void OnStart()
{
func(Expression2);
func(Expression3);
func(Expression1?Expression2:Expression3);
func(!Expression1?Expression2:Expression3);
}
//
Result:
//
//
//
//
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
128
Language Basics
Switch Operator
Compares the expression value with constants in all the case variants and passes control to the
operator that corresponds to the expression value. Each variant of case can be marked with an integer
constant, a literal constant or a constant expression. The constant expression can't contain variables
or function calls. Expression of the switch operator must be of integer type int or uint.
switch(expression)
{
case constant: operators
case constant: operators
...
default: operators
}
Operators marked by the default label are executed if none of the constants in case operators is equal
to the expression value. The default variant should not be necessarily declared and should not be
necessarily the last one. If none of the constants corresponds to the expression value and the default
variant is not available, no actions are executed.
The case keyword with a constant are just labels, and if operators are executed for some case variant,
the program will further execute the operators of all subsequent variants until the break operator
occurs. It allows to bind a sequence of operators with several variants.
A constant expression is calculated during compilation. No two constants in one switch operator can
have the same value.
Examples:
//--- First example
switch(x)
{
case 'A':
Print("CASE A");
break;
case 'B':
case 'C':
Print("CASE B or C");
break;
default:
Print("NOT A, B or C");
break;
}
//---
Second example
string res="";
int i=0;
switch(i)
{
case 1:
res=i;break;
129
Language Basics
default:
res="default";break;
case 2:
res=i;break;
case 3:
res=i;break;
}
Print(res);
/*
Result
default
*/
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
130
Language Basics
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:
while(k<n && !IsStopped())
{
y=y*x;
k++;
}
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
131
Language Basics
Expression1 describes the loop initialization. Expression2 checks the conditions of the loop
termination. If it is true, the loop body for is executed. The loop repeats expression2 until it becomes
false. If it is false, the loop is terminated, and control is given to the next operator. Expression3 is
calculated after each iteration.
The for operator is equivalent to the following succession of operators:
expression1;
while(expression2)
{
operator;
expression3;
};
Any of the three or all three expressions can be absent in the for operator, but the semicolons (;) that
separate them must not be omitted. If expression2 is omitted, it is considered constantly true. The
for(;;) operator is a continuous loop, equivalent to the while(1) operator. Each expression 1 or 3 can
consist of several expressions combined by a comma operator ','.
Note
If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the 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
132
Language Basics
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:
//--- Calculate the Fibonacci series
int counterFibonacci=15;
int i=0,first=0,second=1;
int currentFibonacciNumber;
do
{
currentFibonacciNumber=first+second;
Print("i = ",i,"
currentFibonacciNumber = ",currentFibonacciNumber);
first=second;
second=currentFibonacciNumber;
i++; // without this operator an infinite loop will appear!
}
while(i<counterFibonacci && !IsStopped());
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
133
Language Basics
Break Operator
The break operator terminates the execution of the nearest nested outward switch, while, do-while or
for operator. The control is passed to the operator that follows the terminated one. One of the
purposes of this operator is to finish the looping execution when a certain value is assigned to a
variable.
Example:
//--- searching for the first zero element
for(i=0;i<array_size;i++)
if(array[i]==0)
break;
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
134
Language Basics
Continue Operator
The continue operator passes control to the beginning of the nearest outward loop while, do-while or
for operator, the next iteration being called. The purpose of this operator is opposite to that of break
operator.
Example:
//--- Sum of all nonzero elements
int func(int array[])
{
int array_size=ArraySize(array);
int sum=0;
for(int i=0;i<array_size; i++)
{
if(a[i]==0) continue;
sum+=a[i];
}
return(sum);
}
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
135
Language Basics
//+------------------------------------------------------------------+
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();
}
//--}
136
Language Basics
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
137
Language Basics
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:
double
// return value
The return operator can return the value of an expression located in this operator. If necessary, the
expression value is converted to the function result type. 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.
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
138
Language Basics
type.
Example:
int somefunc(double a,
double d=0.0001,
int n=5,
bool b=true,
string s="passed string")
{
Print("Required parameter a = ",a);
Print("Pass the following parameters: d = ",d," n = ",n," b = ",b," s = ",s);
return(0);
}
If any of parameters has a default value, all subsequent parameters must also have default values.
Example of incorrect declaration:
int somefunc(double a,
double d=0.0001,
int n,
bool b,
See also
Overload, Virtual Functions, Polymorphism
139
Language Basics
Function Call
If a name that has not been described before, appears in the expression and is followed by the left
parenthesis, it is contextually considered as the name of a function.
function_name (x1, x2,..., xn)
Arguments (formal parameters) are passed by value, i.e. each expression x1,..., xn is calculated, and
the value is passed to the function. The order of expressions calculation and the order of values
loading are not guaranteed. During the execution, the system checks the number and type of
arguments passed to the function. 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:
void somefunc(double init,
double sec=0.0001, //set default values
int level=10);
//...
somefunc();
somefunc(3.14);
// Correct call
somefunc(3.14,0.0002);
// Correct call
somefunc(3.14,0.0002,10);
// Correct call
When calling a function, one may not skip parameters, even those having default values:
somefunc(3.14, , 10);
See also
Overload, Virtual Functions, Polymorphism
140
Language Basics
Passing Parameters
There are two methods, by which the machine language can pass arguments to a subprogram
(function). The first method is to send a parameter by value. This method copies the argument value
into a formal function parameter. Therefore, any changes in this parameter within the function have
no influence on the corresponding call argument.
//+------------------------------------------------------------------+
//| Passing parameters by value
//+------------------------------------------------------------------+
double FirstMethod(int i,int j)
{
double res;
//--i*=2;
j/=2;
res=i+j;
//--return(res);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--int a=14,b=8;
Print("a and b before call:",a," ",b);
double d=FirstMethod(a,b);
Print("a and b after call:",a," ",b);
}
//--- Result of script execution
//
//
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;
141
Language Basics
//--return(res);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--int a=14,b=8;
Print("a and b before call:",a," ",b);
double d=SecondMethod(a,b);
Print("a and b after call:",a," ",b);
}
//+------------------------------------------------------------------+
//--- result of script execution
//
//
MQL5 uses both methods, with one exception: arrays, structure type variables and class objects are
always passed by reference. In order to avoid changes in actual parameters (arguments passed at
function call) use the access specifier const. 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 opening parenthesis.
Example:
void OnStart()
{
//--int a[]={0,1,2};
int i=0;
func(a[i],a[i++],"First call (i = "+string(i)+")");
func(a[i++],a[i],"Second call (i = "+string(i)+")");
// Result:
// First call (i = 0) : par1 = 1
// Second call (i = 1) : par1 = 1
par2 = 0
par2 = 1
}
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void func(int par1,int par2,string comment)
{
142
Language Basics
Print(comment,": par1 = ",par1,"
par2 = ",par2);
In first call (see example above) the i variable is first used in strings concatenation:
"First call (i = "+string(i)+")"
Here its value doesn't change. Then the i variable is used in calculation of the a[i++] array element,
i.e. when array element with index i is accessed, the i variable is incremented. And only after that the
first parameter with changed value of i variable is calculated.
In the second call the same value of i (calculated on the first phase of function calling) is used when
calculating all three parameters. Only after the first parameters is calculated the i variable is changed
again.
See also
Visibility Scope and Lifetime of Variables, Overload, Virtual Functions, Polymorphism
143
Language Basics
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];
}
aver=sum/size;
//+------------------------------------------------------------------+
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];
}
aver=(double)sum/size;// Give the amount of type double, and divide
//--Print("Calculation of the average for an array of int type");
return aver;
}
Each function contains the message output via the Print() function;
Print("Calculation of the average for an array of int type");
The compiler selects a necessary function in accordance with the types of arguments and their
144
Language Basics
quantity. The rule, according to which the choice is made, is called the signature matching algorithm.
A signature is a list of types used in the function declaration.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--int
a[5]={1,2,3,4,5};
double b[5]={1.1,2.2,3.3,4.4,5.5};
double int_aver=AverageFromArray(a,5);
double double_aver=AverageFromArray(b,5);
Print("int_aver = ",int_aver,"
double_aver = ",double_aver);
}
//--- Result of the script
// Calculate the average for an array of int type
// Calculate the average for an array of double type
// int_aver= 3.00000000
double_aver= 3.30000000
Function overloading is a process of creating several functions with the same name, but different
parameters. This means that in overloaded variants of a function, the number of arguments and/or
their type must be different. A specific function variant is selected based on the correspondence of
the list of arguments when calling the function, to the list of parameters in the function declaration.
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 castings of what types are present. The
best correspondence must be unique. An overloaded function must be the best match among all the
other variants for at least one argument. At the same time it must match for all other arguments not
worse than other variants.
Below is a matching algorithm for each argument.
145
Language Basics
If you doubt, use explicit conversion to ensure strict compliance.
Examples of overloaded functions in MQL5 can be seen in the example of ArrayInitialize() functions.
Function overloading rules apply to overload of class methods.
Overloading of system functions is allowed, but it should be observed that the compiler is able to
accurately select the necessary function. For example, we can overload the system function MathMax()
in 4 different ways, but only two variants are correct.
Example:
// 1. overload is allowed - function differs from built-in MathMax() function in the number of para
double MathMax(double a,double b,double c);
// 2. overload is not allowed!
// number of parameters is different, but the last has a default value
// this leads to the concealment of the system function when calling, which is unacceptable
double MathMax(double a,double b,double c=DBL_MIN);
// 3. overload is allowed - normal overload by type of parameters a and b
double MathMax(int a,int b);
// 4. overload is not allowed!
// the number and types of parameters are the same as in original double MathMax(double a,double b)
int MathMax(double a,double b);
See also
Overload, Virtual Functions, Polymorphism
146
Language Basics
Operation Overloading
For ease of code reading and writing, overloading of some operations is allowed. Overloading operator
is written using the keyword operator. The following operators can be overloaded:
binary +,-,/,*,%,<<,>>,==,!=,<,>,<=,>=,=,+=,-=,/=,*=,%=,&=,|=,^=,<<=,>>=,&&,||,&,|,^
unary +,-,++,--,!,~
assignment operator =
indexing operator []
Operation overloading allows the use of the operating notation (written in the form of simple
expressions) for complex objects - structures and classes. Writing expressions using overloaded
operations simplifies the view of the source code, because a more complex implementation is hidden.
For example, consider complex numbers, which consist of real and imaginary parts. They are widely
used in mathematics. The MQL5 language has no data type to represent complex numbers, but it is
possible to create a new data type in the form of a structure or class. Declare the complex structure
and define four methods that implement four arithmetic operations:
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers
//+------------------------------------------------------------------+
struct complex
{
double
double
//--- Constructors
complex():re(0.0),im(0.0) {
// Addition
complex
// Subtraction
complex
// Multiplication
complex
// Division
};
Now, in our code we can declare variables representing complex numbers, and work with them.
For example:
void OnStart()
{
//--- Declare and initialize variables of a complex type
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f,
b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
147
Language Basics
z=a.Add(a,b);
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers
z=a.Mul(a,b);
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a.Div(a,b);
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--}
But it would be more convenient to use usual operators "+", "-", "*" and "/" for ordinary arithmetic
operations with complex numbers.
Keyword operator is used for defining a member function that performs type conversion. Unary and
binary operations for class object variables can be overloaded as non-static member functions. They
implicitly act on the class object.
Most binary operations can be overloaded like regular functions that take one or both arguments as a
class variable or a pointer to an object of this class. For our type complex, overloading in the
declaration will look like this:
//--- Operators
complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f,
b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//a.re=5;
//a.im=1;
//b.re=-1;
//b.im=-5;
//--- Sum up two numbers
complex z=a+b;
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers
z=a*b;
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a/b;
148
Language Basics
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--}
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers
//+------------------------------------------------------------------+
struct complex
{
double
double
//--- Constructors
complex():re(0.0),im(0.0) {
// Addition
complex
// Subtraction
complex
// Multiplication
complex
// Division
//+------------------------------------------------------------------+
complex complex::Add(const complex &l,const complex &r) const
{
complex res;
//--res.re=l.re+r.re;
res.im=l.im+r.im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Subtraction
//+------------------------------------------------------------------+
complex complex::Sub(const complex &l,const complex &r) const
{
complex res;
//--res.re=l.re-r.re;
res.im=l.im-r.im;
//--- Result
return res;
149
Language Basics
}
//+------------------------------------------------------------------+
//| Multiplication
//+------------------------------------------------------------------+
complex complex::Mul(const complex &l,const complex &r) const
{
complex res;
//--res.re=l.re*r.re-l.im*r.im;
res.im=l.re*r.im+l.im*r.re;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Division
//+------------------------------------------------------------------+
complex complex::Div(const complex &l,const complex &r) const
{
//--- Empty complex number
complex res(EMPTY_VALUE,EMPTY_VALUE);
//--- Check for zero
if(r.re==0 && r.im==0)
{
Print(__FUNCTION__+": number is zero");
return(res);
}
//--- Auxiliary variables
double e;
double f;
//--- Selecting calculation variant
if(MathAbs(r.im)<MathAbs(r.re))
{
e = r.im/r.re;
f = r.re+r.im*e;
res.re=(l.re+l.im*e)/f;
res.im=(l.im-l.re*e)/f;
}
else
{
e = r.re/r.im;
f = r.im+r.re*e;
res.re=(l.im+l.re*e)/f;
res.im=(-l.re+l.im*e)/f;
}
//--- Result
return res;
}
150
Language Basics
Most unary operations for classes can be overloaded as ordinary functions that accept a single class
object argument or a pointer to it. Add overloading of unary operations "-" and "!".
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers
//+------------------------------------------------------------------+
struct complex
{
double
re;
// Real part
double
im;
// Imaginary part
...
//--- Unary operators
complex operator-()
bool
const; // Negation
operator!()
};
...
//+------------------------------------------------------------------+
//| Overloading the "unary minus" operator
//+------------------------------------------------------------------+
complex complex::operator-() const
{
complex res;
//--res.re=-re;
res.im=-im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Overloading the "logical negation" operator
//+------------------------------------------------------------------+
bool complex::operator!() const
{
//--- Are the real and imaginary parts of the complex number equal to zero?
return (re!=0 && im!=0);
}
Now we can check the value of a complex number for zero and get a negative value:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f,
b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
151
Language Basics
complex z=a/b;
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--- A complex number is equal to zero by default (in the default constructor re==0 and im==0)
complex zero;
Print("!zero=",!zero);
//--- Assign a negative value
zero=-z;
PrintFormat("z=%.2f+i*%.2f,
zero=%.2f+i*%.2f",z.re,z.im, zero.re,zero.im);
PrintFormat("-zero=%.2f+i*%.2f",-zero.re,-zero.im);
//--- Check for zero once again
Print("!zero=",!zero);
//--}
Note that we did not have to overload the assignment operator "=", as structures of simple types can
be directly copied one into each other. Thus, we can now write a code for calculations involving
complex numbers in the usual manner.
Overloading of the indexing operator allows to obtain the values of the arrays enclosed in an object, in
a simple and familiar way, and it also contributes to a better readability of the source code. For
example, we need to provide access to a symbol in the string at the specified position. A string in
MQL5 is a separate type string, which is not an array of symbols, but with the help of an overloaded
indexing operation we can provide a simple and transparent work in the generated CString class:
//+------------------------------------------------------------------+
//| Class to access symbols in string as in array of symbols
//+------------------------------------------------------------------+
class CString
{
string
m_string;
public:
CString(string str=NULL):m_string(str) { }
ushort operator[] (int x) { return(StringGetCharacter(m_string,x)); }
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- An array for receiving symbols from a string
int
x[]={ 19,4,18,19,27,14,15,4,17,0,19,14,17,27,26,28,27,5,14,
17,27,2,11,0,18,18,27,29,30,19,17,8,13,6 };
res;
152
Language Basics
//--- Show the result
Print(res);
}
Another example of overloading of the indexing operation is operations with matrices. The matrix
represents a two-dimensional dynamic array, the array size is not defined in advance. Therefore, you
cannot declare an array of form array[][] without specifying the size of the second dimension, and
then pass this array as a parameter. A possible solution is a special class CMatrix, which contains an
array of CRow class objects.
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Operations of addition and multiplication of matrices
CMatrix A(3),B(3),C();
//--- Prepare an array for rows
double a1[3]={1,2,3}, a2[3]={2,3,1}, a3[3]={3,1,2};
double b1[3]={3,2,1}, b2[3]={1,3,2}, b3[3]={2,1,3};
//--- Fill the matrices
A[0]=a1; A[1]=a2; A[2]=a3;
B[0]=b1; B[1]=b2; B[2]=b3;
//--- Output the matrices in the Experts log
Print("---- Elements of matrix A");
Print(A.String());
Print("---- Elements of matrix B");
Print(B.String());
//--- Addition of matrices
Print("---- Addition of matrices A and B");
C=A+B;
//--- Output the formatted string representation
Print(C.String());
//--- Multiplication of matrices
Print("---- Multiplication of matrices A and B");
C=A*B;
Print(C.String());
//--- Now we show how to get values in the style of dynamic arrays matrix[i][j]
Print("Output the values of matrix C elementwise");
//--- Go through the matrix rows - CRow objects - in a loop
for(int i=0;i<3;i++)
{
string com="| ";
//--- Form rows from the matrix for the value
for(int j=0;j<3;j++)
{
153
Language Basics
//--- Get the matrix element by the number of the row and column
double element=C[i][j];// [i] - Access to CRow in the array m_rows[] ,
// [j] - Overloaded operator of indexing in CRow
com=com+StringFormat("a(%d,%d)=%G ; ",i,j,element);
}
com+="|";
//--- Output the values of the row
Print(com);
}
}
//+------------------------------------------------------------------+
//| Class "Row"
//+------------------------------------------------------------------+
class CRow
{
private:
double
m_array[];
public:
//--- Constructors and a destructor
CRow(void)
{ ArrayResize(m_array,0);
}
}
Size(void) const
{ return(ArraySize(m_array));}
String(void) const;
operator[](int i) const
{ return(m_array[i]);
operator=(const double
void
&array[]); // An array
// Another CRow object
double
};
//+------------------------------------------------------------------+
//| Constructor for initializing a row with an array
//+------------------------------------------------------------------+
void
{
int size=ArraySize(array);
//--- If the array is not empty
if(size>0)
{
ArrayResize(m_array,size);
//--- Fill with values
for(int i=0;i<size;i++)
m_array[i]=array[i];
}
//---
154
Language Basics
}
//+------------------------------------------------------------------+
//| Assignment operation for the array
//+------------------------------------------------------------------+
void CRow::operator=(const double &array[])
{
int size=ArraySize(array);
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=array[i];
//--}
//+------------------------------------------------------------------+
//| Assignment operation for CRow
//+------------------------------------------------------------------+
void CRow::operator=(const CRow
&r)
{
int size=r.Size();
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=r[i];
//--}
//+------------------------------------------------------------------+
//| Operator of multiplication by another row
//+------------------------------------------------------------------+
double CRow::operator*(const CRow &o)
{
double res=0;
//--- Verifications
int size=Size();
if(size!=o.Size() || size==0)
{
Print(__FUNCSIG__,": Failed to multiply two matrices, their sizes are different");
return(res);
}
//--- Multiply arrays elementwise and add the products
for(int i=0;i<size;i++)
res+=m_array[i]*o[i];
//--- Result
return(res);
}
//+------------------------------------------------------------------+
//| Returns a formatted string representation
//+------------------------------------------------------------------+
string CRow::String(void) const
{
155
Language Basics
string out="";
//--- If the size of the array is greater than zero
int size=ArraySize(m_array);
//--- We work only with a non-zero number of array elements
if(size>0)
{
out="{";
for(int i=0;i<size;i++)
{
//--- Collect the values to a string
out+=StringFormat(" %G;",m_array[i]);
}
out+=" }";
}
//--- Result
return(out);
}
//+------------------------------------------------------------------+
//| Class "Matrix"
//+------------------------------------------------------------------+
class CMatrix
{
private:
CRow
m_rows[];
public:
//--- Constructors and a destructor
CMatrix(void);
CMatrix(int rows)
{ ArrayResize(m_rows,rows);
~CMatrix(void){};
//--- Get the matrix sizes
int
Rows()
const { return(ArraySize(m_rows));
int
Cols()
//--- Returns the value of the column in the form of a CRow row
CRow
String(void) const;
{ return(GetPointer(m_rows[i]));
};
//+------------------------------------------------------------------+
//| A default constructor, create an array of rows of zero size
//+------------------------------------------------------------------+
156
Language Basics
CMatrix::CMatrix(void)
{
//--- The zero number of rows in the matrix
ArrayResize(m_rows,0);
//--}
//+------------------------------------------------------------------+
//| Returns the column value in the form of CRow
//+------------------------------------------------------------------+
CRow
{
//--- A variable to get the values from the column
CRow row();
//--- The number of rows in the matrix
int rows=Rows();
//--- If the number of rows is greater than zero, execute the operation
if(rows>0)
{
//--- An array to receive the values of the column with index col_index
double array[];
ArrayResize(array,rows);
//--- Filling the array
for(int i=0;i<rows;i++)
{
//--- Check the number of the column for row i - it may exceed the boundaries of the array
if(col_index>=this[i].Size())
{
Print(__FUNCSIG__,": Error! Column number ",col_index,"> row size ",i);
break; // row will be uninitialized object
}
array[i]=this[i][col_index];
}
//--- Create a CRow row based on the array values
row=array;
}
//--- Result
return(row);
}
//+------------------------------------------------------------------+
//| Addition of two matrices
//+------------------------------------------------------------------+
CMatrix CMatrix::operator+(const CMatrix &m)
{
//--- The number of rows and columns in the passed matrix
int cols=m.Cols();
int rows=m.Rows();
//--- The matrix to receive the addition results
CMatrix res(rows);
//--- The sizes of the matrix must match
157
Language Basics
if(cols!=Cols() || rows!=Rows())
{
//--- Addition impossible
Print(__FUNCSIG__,": Failed to add two matrices, their sizes are different");
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols);
//--- Go through rows to add
for(int i=0;i<rows;i++)
{
//--- Write the results of addition of matrix strings in the array
for(int k=0;k<cols;k++)
{
arr[k]=this[i][k]+m[i][k];
}
//--- Place the array to the matrix row
res[i]=arr;
}
//--- return the result of addition of matrices
return(res);
}
//+------------------------------------------------------------------+
//| Multiplication of two matrices
//+------------------------------------------------------------------+
CMatrix CMatrix::operator*(const CMatrix &m)
{
//--- Number of columns of the first matrix, number of rows passed in the matrix
int cols1=Cols();
int rows2=m.Rows();
int rows1=Rows();
int cols2=m.Cols();
//--- Matrix to receive the addition result
CMatrix res(rows1);
//--- Matrices should be coordinated
if(cols1!=rows2)
{
//--- Multiplication impossible
Print(__FUNCSIG__,": Failed to multiply two matrices, format is not compatible "
"- number of columns in the first factor should be equal to the number of rows in the s
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols1);
//--- Fill the rows in the multiplication matrix
for(int i=0;i<rows1;i++)// Go through rows
{
158
Language Basics
//--- Reset the receiving array
ArrayInitialize(arr,0);
//--- Go through elements in the row
for(int k=0;k<cols1;k++)
{
//--- Take values of column k of the matrix m in the for of CRow
CRow column=m.GetColumnAsRow(k);
//--- Multiply two rows and write the result of scalar multiplication of vectors in the iarr[k]=this[i]*column;
}
//--- place array arr[] in the i-th row of the matrix
res[i]=arr;
}
//--- Return the product of two matrices
return(res);
}
//+------------------------------------------------------------------+
//| Assignment operation
//+------------------------------------------------------------------+
CMatrix *CMatrix::operator=(const CMatrix &m)
{
//--- Find and set the number of rows
int rows=m.Rows();
ArrayResize(m_rows,rows);
//--- Fill our rows with the values of rows of
//+------------------------------------------------------------------+
string CMatrix::String(void) const
{
string out="";
int rows=Rows();
//--- Form string by string
for(int i=0;i<rows;i++)
{
out=out+this[i].String()+"\r\n";
}
//--- Result
return(out);
}
See also
Overloading, Arithmetic Operations, Function Overloading, Precedence Rules
159
Language Basics
int
#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.
Please keep in mind that DLL and EX5 libraries should have different names (regardless of the
directories they are located in) if they are imported together. All imported functions have the scope
resolution corresponding to the library's "file name".
Example:
#import "kernel32.dll"
int GetLastError();
#import "lib.ex5"
int GetLastError();
#import
class CFoo
{
public:
int
GetLastError() { return(12345); }
void
func()
{
Print(GetLastError());
Print(::GetLastError());
}
};
void OnStart()
{
CFoo foo;
foo.func();
}
160
Language Basics
See also
Overload, Virtual Functions, Polymorphism
161
Language Basics
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.
int Function() export
{
}
This modifier orders the compiler to add the function into the table of EX5 functions exported by this
ex5 file. Only function with such a modifier are accessible ("visible") from other mql5 programs.
The library property tells the compiler that the EX5-file will be a library, and the compiler will show it in
the header of EX5.
All functions that are planned as exportable ones must be marked with the export modifier.
See also
Overload, Virtual Functions, Polymorphism
162
Language Basics
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.
To optimize input parameters of an Expert Advisor, it is recommended to use values of the
ENUM_INIT_RETCODE enumeration as the return code. These values are used for organizing the course
of optimization, including the selection of the most appropriate testing agents. During initialization of
an Expert Advisor before the start of testing you can request information about the configuration and
resources of an agent (the number of cores, amount of free memory, etc.) using the
TerminalInfoInteger() function. Based on the information obtained, you can either allow to use this
testing agent, or reject using it during the optimization of this Expert Advisor.
ENUM_INIT_RETCODE
Identifier
Description
INIT_SUCCEEDED
INIT_FAILED
163
Language Basics
INIT_AGENT_NOT_SUITABLE
The OnInit() function of the void type always denotes successful initialization.
OnDeinit
The OnDeinit() function is called during deinitialization and is the Deinit event handler. It must be
declared as the void type and should have one parameter of the const int type, which contains the
code of deinitialization reason. If a different type is declared, the compiler will generate a warning,
but the function will not be called. For scripts the Deinit event is not generated and therefore the
OnDeinit() function can't be used in scripts.
void OnDeinit(const int reason);
The Deinit event is generated for Expert Advisors and indicators in the following cases:
before reinitialization due to the change of a symbol or chart period, to which the mql5 program is
attached;
before reinitialization due to the change of input parameters;
before unloading the mql5 program.
OnTick
The NewTick event is generated for Expert Advisors only when a new tick for a symbol is received, to
the chart of which the Expert Advisor is attached. It's useless to define the OnTick() function in a
custom indicator or script, because the NewTick event is not generated for them.
The Tick event is generated only for Expert Advisors, but this does not mean that Expert Advisors
required the OnTick() function, since not only NewTick events are generated for Expert Advisors, but
also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type,
with no parameters:
void OnTick();
164
Language Basics
OnTimer
The OnTimer() function is called when the Timer event occurs, which is generated by the system timer
only for Expert Advisors and indicators - it can't be used in scripts. The frequency of the event
occurrence is set when subscribing to notifications about this event to be received by the
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 the mql5 program stops operating, the timer is destroyed forcibly, if it was created
but hasn't been disabled by the EventKillTimer() function.
OnTrade
The function is called when the Trade event occurs, which appears when you change the list of placed
orders and open positions, the history of orders and history of deals. When a trade activity is
performed (pending order opening, position opening/closing, stops setting, pending order triggering,
etc.) the history of orders and deals and/or list of positions and current orders is changed accordingly.
void OnTrade();
Users must independently implement in the code the verification of a trade account state when such
an event is received (if this is required by the trade strategy conditions). If the 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 a user remembers the ticket
value, he/she will be able to find out what happened to the order using this value during OnTrade()
event handling.
OnTradeTransaction
When performing some definite actions on a trade account, its state changes. Such actions include:
Sending a trade request from any MQL5 application in the client terminal using OrderSend and
165
Language Basics
changing positions.
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions. Arrival of such a transaction at the terminal is a
TradeTransaction event. It calls OnTradeTransaction handler
void OnTradeTransaction(
const MqlTradeTransaction&
trans,
const MqlTradeRequest&
request,
// request structure
const MqlTradeResult&
result
// result structure
);
a trade account;
request - this parameter gets MqlTradeRequest structure describing a trade request;
result - this parameter gets MqlTradeResult structure describing a trade request execution result.
depending on a transaction type. For example, only type field (trade transaction type) must be
analyzed for TRADE_TRANSACTION_REQUEST type transactions. The second and third
parameters of OnTradeTransaction function (request and result) must be analyzed for additional
data. For more information, see "Structure of a Trade Transaction".
A trade transaction description does not deliver all available information concerning orders,
deals and positions (e.g., comments). OrderGet*, HistoryOrderGet*, HistoryDealGet* and
PositionGet* functions should be used to get extended information.
After applying trade transactions for a client account, they are consistently placed to the terminal
trade transactions queue, from which they consistently sent to OnTradeTransaction entry point in
order of arrival at the terminal.
When handling trade transactions by an Expert Advisor using OnTradeTransaction handler, the
terminal continues handling newly arrived trade transactions. Therefore, the state of a trade account
can change during OnTradeTransaction operation already. For example, while an MQL5 program
handles an event of adding a new order, it may be executed, deleted from the list of the open ones
166
Language Basics
and moved to the history. Further on, the application will be notified of these events.
Transactions queue length comprises 1024 elements. If OnTradeTransaction handles a new transaction
for too long, the old ones in the queue may be superseded by the newer ones.
Generally, there is no accurate ratio of the number of OnTrade and OnTradeTransaction calls.
OnTester
The OnTester() function is the handler of the Tester event that is automatically generated after a
history testing of an Expert Advisor on the chosen interval is over. The function must be defined with
the double type, with no parameters:
double OnTester();
The function is called right before the call of OnDeinit() and has the same type of the return value double. OnTester() can be used only in the testing of Expert Advisors. Its main purpose is to calculate
a certain value that is used as the Custom max criterion in the genetic optimization of input
parameters.
In the genetic optimization descending sorting is applied to results within one generation. I.e. from
the point of view of the optimization criterion, the best results are those with largest values (for the
Custom max optimization criterion values returned by the OnTester function are taken into account).
In such a sorting, the worst values are positioned at the end and further thrown off and do not
participate in the forming of the next generation.
OnTesterInit
The OnTesterInit() function is the handler of the TesterInit event, which is automatically generated
before the start of Expert Advisor optimization in the strategy tester. The function must be defined
with the void type. It has no parameters:
void OnTesterInit();
With the start of optimization, an Expert Advisor with the OnTesterDeinit() or OnTesterPass() handler
is automatically loaded in a separate terminal chart with the symbol and period specified in the tester,
and receives the TesterInit event. The function is used for Expert Advisor initialization before the
start of optimization for further processing of optimization results.
OnTesterPass
The OnTesterPass() function is the handler of the TesterPass event, which is automatically generated
when a frame is received during Expert Advisor optimization in the strategy tester. The function must
be defined with the void type. It has no parameters:
void OnTesterPass();
An Expert Advisor with the OnTesterPass() handler is automatically loaded in a separate terminal chart
with the symbol/period specified for testing, and gets TesterPass events when a frame is received
during optimization. The function is used for dynamic handling of optimization results "on the spot"
167
Language Basics
without waiting for its completion. Frames are added using the FrameAdd() function, which can be
called after the end of a single pass in the OnTester() handler.
OnTesterDeinit
OnTesterDeinit() is the handler of the TesterDeinit event, which is automatically generated after the
end of Expert Advisor optimization in the strategy tester. The function must be defined with the void
type. It has no parameters:
void OnTesterDeinit();
An Expert Advisor with the TesterDeinit() handler is automatically loaded on a chart at the start of
optimization, and receives TesterDeinit after its completion. The function is used for final processing
of all optimization results.
OnBookEvent
The OnBookEvent() function is the BookEvent handler. BookEvent is generated for Expert Advisors and
indicators when Depth of Market changes. It must be of the void type and have one parameter of the
string type:
void OnBookEvent (const string& symbol);
To receive BookEvent events for any symbol, you just need to pre-subscribe to receive these events
for this symbol using the MarketBookAdd() function. In order to unsubscribe from receiving the
BookEvent events for a particular symbol, call 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
OnChartEvent() is the handler of a group of ChartEvent events:
CHARTEVENT_KEYDOWN event of a keystroke, when the chart window is focused;
CHARTEVENT_MOUSE_MOVE
and
CHARTEVENT_OBJECT_CREATE
event
of
graphical
CHART_EVENT_OBJECT_CREATE=true is set for the chart);
mouse
click
object
events
creation
(if
(if
event
of
graphical
CHART_EVENT_OBJECT_DELETE=true is set for the chart);
object
deletion
(if
168
Language Basics
CHARTEVENT_CUSTOM+n ID of the user event, where n is in the range from 0 to 65535.
CHARTEVENT_CUSTOM_LAST the last acceptable ID of a custom event (CHARTEVENT_CUSTOM
+65535).
The function can be called only in Expert Advisors and indicators. The function should be of void type
with 4 parameters:
void OnChartEvent(const int id,
// Event ID
);
For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through these parameters
are listed in the table below.
Event
Value of the id
parameter
Value of
lparam
parameter
the
CHARTEVENT_KE
YDOWN
code
of
pressed key
CHARTEVENT_MO
USE_MOVE
Event
of
graphical object
creation
(if
CHART_EVENT_O
BJECT_CREATE=t
rue is set for the
chart)
Event
of
keystroke
Value of
dparam
parameter
the
Value of
sparam
parameter
the
Repeat
count
(the number of
times
the
keystroke
is
repeated as a
result of the user
holding down the
key)
the X coordinate
the Y coordinate
CHARTEVENT_OB
JECT_CREATE
Name of the
created graphical
object
Event of change
of an object
property via the
properties dialog
CHARTEVENT_OB
JECT_CHANGE
Name of the
modified
graphical object
Event
of
graphical object
deletion
(if
CHARTEVENT_OB
JECT_DELETE
Name of the
deleted graphical
object
169
Language Basics
CHART_EVENT_O
BJECT_DELETE=t
rue is set for the
chart)
Event
of
a
mouse click on
the chart
CHARTEVENT_C
LICK
the X coordinate
the Y coordinate
Event
of
a
mouse click in a
graphical object
belonging to the
chart
CHARTEVENT_OB
JECT_CLICK
the X coordinate
the Y coordinate
Name of the
graphical object,
on which the
event occurred
Event
of
a
graphical object
dragging using
the mouse
CHARTEVENT_OB
JECT_DRAG
Name of the
moved graphical
object
Event of the
finished
text
editing in the
entry box of the
LabelEdit
graphical object
CHARTEVENT_OB
JECT_ENDEDIT
Name of the
LabelEdit
graphical object,
in which text
editing
has
completed
Event of chart
Changes
CHARTEVENT_C
HART_CHANGE
ID of the user
event under the
N number
CHARTEVENT_CU
STOM+N
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.
int OnCalculate (const int rates_total,
// array to calculate
);
As the price[] array, one of timeseries or a calculated buffer of some indicator can be passed. To
170
Language Basics
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.
Necessary time series or an indicator to be used as the price[] array can be selected by the user in the
"Parameters" tab when starting the indicator. To do this, you should specify the necessary item in the
drop-down list of "Apply to" field.
To receive values of a custom indicator from other mql5 programs, the iCustom() function is used,
which returns the indicator handle for subsequent operations. You can also specify the appropriate
price[] array or the handle of another indicator. This parameter should be transmitted last in the list
of input variables of the custom indicator.
Example:
void OnStart()
{
//--string terminal_path=TerminalInfoString(STATUS_TERMINAL_PATH);
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 time series is used for
calculations.
171
Language Basics
int OnCalculate (const int rates_total,
// Time
// Open
// High
// Low
// Close
// Tick Volume
// Real Volume
// Spread
);
Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and low prices
and close prices of the current time frame. The time[] parameter contains an array with open time
values, the spread[] parameter has an array containing the history of spreads (if any spread is
provided for the traded security). The parameters of volume[] and tick_volume[] contain the history of
trade and tick volume, respectively.
To determine the indexing direction of time[], open[], high[], low[], close[], tick_volume[], volume[]
and spread[], call 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 note the connection between the return value of OnCalculate() and the second input
parameter prev_calculated. During the function call, the prev_calculated parameter contains a value
returned by OnCalculate() during previous call. This allows for economical algorithms for calculating
the custom indicator in order to avoid repeated calculations for those bars that haven't changed since
the previous run of this function.
For this, it is usually enough to return the value of the rates_total parameter, which contains the
number of bars in the current function call. If since the last call of OnCalculate() price data has
changed (a deeper history downloaded or history blanks filled), the value of the input parameter
prev_calculated will be set to zero by the terminal.
Note: if OnCalculate returns zero, then the indicator values are not shown in the DataWindow of the
client terminal.
To understand it better, it would be useful to start the indicator, which code is attached below.
Indicator Example:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Line"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrDarkBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
172
Language Basics
//--- indicator buffers
double
LineBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& time[],
const double& open[],
const double& high[],
const double& low[],
const double& close[],
const long& tick_volume[],
const long& volume[],
const int& spread[])
{
//--- Get the number of bars available for the current symbol and chart period
int bars=Bars(Symbol(),0);
Print("Bars = ",bars,", rates_total = ",rates_total,",
prev_calculated = ",prev_calculated);
See also
Running Programs, Client Terminal Events, Working with Events
173
Language Basics
Variables
Declaring Variables
Variables must be declared before they are used. Unique names are used to identify variables. To
declare a variable, you must specify its type and a unique name. Declaration of variable is not an
operator.
Simple types are:
char, short, int, long, uchar, ushort, uint, ulong integers;
color integer representing the RGB-color;
datetime the date and time, an unsigned integer containing the number of seconds since 0 hour
January 1, 1970;
bool boolean values true and false;
double double-precision floating point number;
float single-precision floating point number;
string character strings.
Examples:
string szInfoBox;
int
nOrders;
double dSymbolPrice;
bool
bLog;
datetime tBegin_Data
color
= D'2004.01.01 00:00';
cModify_Color = C'0x44,0xB9,0xE6';
// 0-23
int minute;
// 0-59
int second;
// 0-59
};
...
MyTime strTime; // Variable of the previously declared structure MyTime
You can't declare variables of the structure type until you declare the structure.
Arrays
Array is the indexed sequence of identical-type data:
int
a[50];
double m[7][50];
MyTime t[100];
174
Language Basics
Only an integer can be an array index. No more than four-dimensional arrays are allowed. Numbering
of array elements starts with 0. The last element of a one-dimensional array has the number which is 1
less than the array size. This means that call for the last element of an array consisting of 50 integers
will appear as a[49]. The same concerns multidimensional arrays: A dimension is indexed from 0 to
the dimension size-1. The last element of a two-dimensional array from the example will appear as
m[6][49].
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.
Example:
int OnCalculate (const int rates_total,
// array to calculate
);
this method should be placed in the table of virtual functions of the class.
Storage Classes
There are three storage classes: static, input and extern. These modifiers of a storage class explicitly
indicate to the compiler that corresponding variables are distributed in a pre-allocated area of
memory, which is called the global pool. Besides, these modifiers indicate the special processing of
variable data. If a variable declared on a local level is not a static one, memory for such a variable is
allocated automatically at a program stack. Freeing of memory allocated for a non-static array is also
performed automatically when going beyond the visibility area of the block, in which the array is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects, Static Members of a Class
175
Language Basics
Local Variables
A variable declared inside a function is local. The scope of a local variable is limited to the function
range inside which it is declared. Local variable can be initialized by outcome of any expression. Every
call of the function initializes a local variable. Local variables are stored in memory area of the
corresponding function.
Example:
int somefunc()
{
int ret_code=0;
...
return(ret_code);
}
Scope of a variable is a program part, in which a variable can be referred to. Variables declared inside
a block (at the internal level), have the block as their scope. The block scope start with the variable
declaration and ends with the final right brace.
Local variables declared in the beginning of a function also have the scope of block, as well as function
parameters that are local variables. Any block can contain variable declarations. If blocks are nested
and the identifier in the external block has the same name as the identifier in the internal block, the
external block identifier is hidden, until the operation of the internal block is over.
Example:
void OnStart()
{
//--int i=5;
{
int i=10;
// function variable
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;
for(int i=0;i<3;i++)
Print("Inside for i = ",i);
Print("Outside the block i = ",i);
}
/* Execution result
176
Language Basics
Inside for i = 0
Inside for i = 1
Inside for i = 2
Outside block i = 5
*/
Local variables declared as static have the scope of the block, despite the fact that they exist since
the program start.
Stack
In every MQL5 program, a special memory area called stack is allocated for storing local function
variables that are created automatically. One stack is allocated for all functions. The default stack size
is 256 kb, the stack size can be managed using the #property stacksize compiler directive.
Static local variables are stored in the same place where other static and global variables are stored in a special memory area, which exists separately from the stack. Dynamically created variables also
use a memory area separate from the stack.
With each function call, a place on the stack is allocated for internal non-static variables. After exiting
the function, the memory is available for use again.
If from the first function the second one is called, then the second function occupies the required size
from the remaining stack memory for its variables. Thus, when using included functions, stack
memory will be sequentially occupied for each function. This may lead to a shortage of memory during
one of the function calls, such a situation is called stack overflow.
Therefore, for large local data you should better use dynamic memory - when entering a function,
allocate the memory, which is required for local needs, in the system (new, ArrayResize()), and when
exiting the function, release the memory (delete, ArrayFree()).
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects
177
Language Basics
Formal Parameters
Parameters passed to the function are local. The scope is the function block. Formal parameters must
have names differing from those of external variables and local variables defined within one function.
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:
void func(const int & x[], double y, bool z)
{
if(y>0.0 && !z)
Print(x[0]);
...
}
Formal parameters can be initialized by constants. In this case, the initializing value is considered as
the default value. Parameters, next to the initialized one, must also be initialized.
Example:
void func(int x, double y = 0.0, bool z = true)
{
...
}
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 reflected in the calling function. Arrays of any type
and data of the structure type are always passed by reference. If it is necessary to prohibit modifying
the array or structure contents, the parameters of these types must be declared with the const
keyword.
There is an opportunity to pass parameters of simple types by reference. In this case, modification of
such parameters inside the calling function will affect the corresponding variables passed by reference.
In order to indicate that a parameter is passed by reference, put the & modifier after the data type.
Example:
void func(int& x, double& y, double & z[])
{
double calculated_tp;
...
for(int i=0; i<OrdersTotal(); i++)
{
if(i==ArraySize(z))
break;
if(OrderSelect(i)==false) break;
178
Language Basics
z[i]=OrderOpenPrice();
}
x=i;
y=calculated_tp;
}
179
Language Basics
Static Variables
The storage class of static defines a static variable. The static modifier is indicated before the data
type.
Example:
int somefunc()
{
static int flag=10;
...
return(flag);
}
A static variable can be initialized by a constant or constant expression corresponding to its type,
unlike a simple local variable, which can be initialized by any expression.
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 declared on a local level is not a static one, memory for such a variable is allocated
automatically at a program stack.
Example:
int Counter()
{
static int count;
count++;
if(count%100==0) Print("Function Counter has been called ",count," times");
return count;
}
void OnStart()
{
//--int c=345;
for(int i=0;i<1000;i++)
{
int c=Counter();
}
Print("c =",c);
}
See also
Data Types, Encapsulation and Extensibility of Types, Initialization of Variables, Visibility Scope and
180
Language Basics
Lifetime of Variables, Creating and Deleting Objects, Static Class Members
181
Language Basics
Global Variables
Global variables are created by placing their declarations outside function descriptions. Global
variables are defined at the same level as functions, i.e., they are not local in any block.
Example:
int GlobalFlag=10;
// Global variable
int OnStart()
{
...
}
The scope of global variables is the entire program. Global variables are accessible from all functions
defined in the program. They are initialized to zero unless another initial value is explicitly defined. A
global variable can be initialized only by a constant or constant expression that corresponds to its type.
Global variables are initialized only once after the program is loaded into the client terminal memory
and before the first handling of the Init event. For global variables representing class objects, during
their initialization the corresponding constructors are called. In scripts global variables are initialized
before handling the Start event.
Note: Variables declared at global level must not be mixed up with the client terminal global variables
that can be accessed using the GlobalVariable...() functions.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects
182
Language Basics
Input Variables
The input storage class defines the external variable. The input modifier is indicated before the data
type. A variable with the input modifier can't be changed inside mql5-programs, such variables can be
accessed for reading only. Values of input variables can be changed only by a user from the program
properties window. External variables are always reinitialized immediately before the OnInit() is
called.
Example:
//--- input parameters
input int
MA_Period=13;
input int
MA_Shift=0;
Input variables determine the input parameters of a program. They are available from the Properties
window of a program.
There is another way to set how your input parameter will look like in the Inputs tab. For this, place a
string comment after the description of an input parameter in the same line. In this way you can make
names of input parameters more understandable for users.
Example:
//--- input parameters
input int
InpMAPeriod=13;
// Smoothing period
input int
InpMAShift=0;
// Smoothing method
183
Language Basics
Note: Arrays and variables of complex types can't act as input variables.
Note: The length of a string comment for Input variables cannot exceed 63 characters.
// Sunday
M=1,
// Monday
T=2,
// Tuesday
W=3,
// Wednesday
Th=4,
// Thursday
184
Language Basics
Fr=5,
// Friday,
St=6,
// Saturday
};
//--- input parameters
input dayOfWeek swapday=W;
In order to enable a user to select a necessary value from the properties window during the script
startup, we use the preprocessor command #property script_show_inputs. 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. In order to select an input value the dropdown 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.
185
Language Basics
sinput
int layers=6;
// Number of layers
// Number of layers
The variable declared with sinput modifier is an input parameter of MQL5 program. The value of this
parameter can be changed when launching the program. However, this variable is not used in the
optimization of input parameters. In other words, its values are not enumerated when searching for
the best set of parameters fitting a specified condition.
The Expert Advisor shown above has 5 external parameters. "Number of layers" is declared to be
sinput and equal to 6. This parameter cannot be changed during a trading strategy optimization. We
can specify the necessary value for it to be used further on. Start, Step and Stop fields are not
available for such a variable.
Therefore, users will not be able to optimize this parameter after we specify sinput modifier for the
variable. In other words, the terminal users will not be able to set initial and final values for it in the
Strategy Tester for automatic enumeration in the specified range during optimization.
However, there is one exception to this rule: sinput variables can be varied in optimization tasks
using ParameterSetRange() function. This function has been introduced specifically for the program
control of available values sets for any input variable including the ones declared as static input
(sinput). The ParameterGetRange() function allows to receive input variables values when
optimization is launched (in OnTesterInit() handler) and to reset a change step value and a range,
within which an optimized parameter values will be enumerated.
In this way, combining the sinput modifier and two functions that work with input parameters, allows
to create a flexible rules for setting optimization intervals of input parameters that depend on values
of another input parameters.
See also
iCustom, Enumerations, Properties of Programs
186
Language Basics
Extern Variables
The extern keyword is used for declaring variable identifiers as identifiers of the static storage class
with global lifetime. These variables exist from the start of the program and memory for them is
allocated and initialized immediately after the start of the program.
You can create programs that consist of multiple source files; in this case a directive to the
preprocessor #include is used. Variables declared as an extern with the same type and identifier can
exist in different source files of one project.
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 initialized extern variables of the same type and with the same identifier is prohibited.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects
187
Language Basics
Initialization of Variables
Any variable can be initialized during definition. If a variable is not initialized explicitly, the value
stored in this variable can be any. Implicit initialization is not used.
Global and static 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
= 1;
string s
= "hello";
double f[]
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};
188
Language Basics
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]);
For structure type variable partial initialization is allowed, as well as for static arrays (with an
implicitly set size). You can initialize one or more first elements of a structure or array, the other
elements will be initialized with zeroes in this case.
See also
Data Types, Encapsulation and Extensibility of Types, Visibility Scope and Lifetime of Variables,
Creating and Deleting Objects
189
Language Basics
i,limit;
sum=0;
//--if(prev_calculated==0)
{
limit=MA_Period+begin;
//--- set empty value for first limit bars
for(i=0; i<limit; i++) LineBuffer[i]=0.0;
//--- calculate first visible value
double firstValue=0;
for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}
firstValue/=(double)weightsum;
LineBuffer[limit-1]=firstValue;
}
else
{
limit=prev_calculated-1;
}
for(i=limit;i<rates_total;i++)
{
sum=0;
190
Language Basics
for(int j=0; j<MA_Period; j++) sum+=(MA_Period-j)*price[i-j];
LineBuffer[i]=sum/weightsum;
}
//--}
Its scope is only the for loop; outside of this loop there is another variable with the same name,
declared at the beginning of the function. In addition, the k variable is declared in the loop body, its
scope is the loop body.
Local variables can be declared with the access specifier static. In this case, the compiler has a
variable in the global pool of memory. Therefore, the lifetime of a static variable is equal to the
lifetime of the program. Here the scope of such a variable is limited to the block in which it is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Creating and
Deleting Objects
191
Language Basics
192
Language Basics
pointer declared on a local level, the delete operator for this pointer must be performed before exiting
the level. Otherwise the pointer will be lost and the explicit deletion of the object will fail.
All 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 the corresponding new operator
is invoked, and are assuredly deleted either by the delete operator or automatically by the executing
system of MQL5 during the program unloading. The order of declaration of pointers of dynamically
created object doesn't influence the order of their initialization. The order of initialization and
deinitialization is fully controlled by the programmer.
Local automatic
variable
Dynamically created
object
Initialization
at the execution of
the new operator
Initialization order
in the order
declaration
in the order
declaration
of
irrespective of the
order of declaration
Deinitialization
when
the
delete
operator is executed
or before a mql5
of
193
Language Basics
program is unloaded
Deinitialization
order
irrespective of the
initialization order
Constructor call
at
mql5
loading
program
at initialization
at the execution of
the new operator
Destructor call
at
mql5
unloading
program
at the execution of
the delete operator
Error logs
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables
194
Language Basics
Preprocessor
Preprocessor is a special subsystem of the MQL5 compiler that is intended for preparation of the
program source code immediately before the program is compiled.
Preprocessor allows enhancement of the source code readability. The code can be structured by
including of specific files containing source codes of mql5-programs. The possibility to assign
mnemonic names to specific constants contributes to enhancement of the code readability.
Preprocessor also allows determining specific parameters of mql5-programs:
Declare constants
Set program properties
Include files in program text
Import functions
Conditional Compilation
If the # symbol is used as the first character in a line of the program, this line is considered as a
preprocessor directive. A preprocessor directive ends with a line feed character.
195
Language Basics
// parameter-free form
// parametric form
The #define directive substitutes expression for all further found entries of identifier in the source
text. The identifier is replaced only if it is a separate token. The identifier is not replaced if it is part
of a comment, part of a string, or part of another longer identifier.
The constant identifier is governed by the same rules as variable names. The value can be of any type:
#define ABC
100
#define PI
3.14
#define COMPANY_NAME
...
void ShowCopyright()
{
Print("Copyright
2001-2009, ",COMPANY_NAME);
Print("http://www.metaquotes.net");
}
expression can consist of several tokens, such as keywords, constants, constant and non-constant
expressions. expression ends with the end of the line and can't be transferred to the next line.
Example:
#define TWO
#define THREE
(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
196
Language Basics
double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=((2+3)*(5-1));
*/
// Result
// c=20
Be sure to enclose parameters in parentheses when using the parameters in expression, as this will
help avoid non-obvious errors that are hard to find. If we rewrite the code without using the brackets,
the result will be different:
// example with two parameters a and b
#define A 2+3
#define B 5-1
#define MUL(a, b) a*b
double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=2+3*5-1;
*/
// Result
// c=16
Print(__FILE__,"(",__LINE__,") :",text)
197
Language Basics
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}
#undef MACRO
void func2()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}
void OnStart()
{
func1();
func2();
}
/* Result:
MACRO is defined in func1
MACRO is not defined in func2
*/
See also
Identifiers, Character Constants
198
Language Basics
The compiler will write declared values in the configuration of the module executed.
Constant
Type
Description
icon
string
link
string
copyright
string
version
string
description
string
stacksize
int
199
Language Basics
for it.
library
indicator_applied_price
indicator_chart_window
indicator_separate_window
in
indicator_height
int
indicator_buffers
int
Number
of
buffers
indicator calculation
indicator_plots
int
indicator_minimum
double
indicator_maximum
double
indicator_labelN
string
indicator_colorN
color
indicator_widthN
int
for
200
Language Basics
indicator_styleN
int
indicator_typeN
int
indicator_levelN
double
Horizontal level of N in a
separate indicator window
indicator_levelcolor
color
indicator_levelwidth
int
indicator_levelstyle
int
script_show_confirm
script_show_inputs
tester_indicator
string
tester_file
string
201
Language Basics
string
Library
name
with
the
extension, in double quotes. A
library can have 'dll' or 'ex5' as
file extension. Libraries that
require testing are defined
automatically. However, if any
of libraries is used by a custom
indicator, this property is
required
"3.70"
#property description "At the moment in the indicator several ZigZags with different algorithms are
#property description "It is possible to embed a large number of other indicators showing the highs
#property description "lows and automatically build from these highs and lows various graphical too
Examples of Specifying a Separate Label for Each Indicator Buffer ( "C open; C high; C low; C
close")
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots
#property indicator_type1
DRAW_CANDLES
#property indicator_width1
#property indicator_label1
202
Language Basics
203
Language Basics
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 included in the
search.
If the file name is enclosed in quotation marks, the search is made in the current directory (which
contains the main source file). The standard directory is not included in the search.
See also
Standard Library, Importing Functions
204
Language Basics
Imported functions can have any names. Functions having the same names but from different modules
can be imported at the same time. Imported functions can have names that coincide with the names
of built-in functions. Operation of scope resolution defines which of the functions should be called.
The order of searching for a file specified after the #import keyword is described in Call of Imported
Functions.
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.
The following can't be used for parameters in imported functions:
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
#import "stdlib.ex5"
string ErrorDescription(int error_code);
int
bool
GetIntValue(int);
double GetDoubleValue(double);
string GetStringValue(string);
double GetArrayItemValue(double &arr[],int,int);
bool
SetArrayItemValue(double &arr[],int,int,double);
205
Language Basics
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
206
Language Basics
// the code located here is compiled if the identifier has already been defined for the preproce
#endif
#ifndef identifier
// the code located here is compiled if the identifier is not currently defined by #define prepr
#endif
Any of the conditional compilation directives can be followed by any number of lines possibly
containing #else directive and ending with #endif. If the verified condition is true, the lines between
#else and #endif are ignored. If the verified condition is not fulfilled, all lines between checking and
#else directive (or #endif directive if the former is absent) are ignored.
Example:
#ifndef TestMode
#define TestMode
#endif
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef TestMode
Print("Test mode");
#else
Print("Normal mode");
#endif
}
Depending on the program type and compilation mode, the standard macros are defined the following
way:
__MQL5__ macro is defined when compiling *.mq5 file, __MQL4__ macro is defined when compiling
*.mq4 one.
_DEBUG macro is defined when compiling in debug mode.
_RELEASE macro is defined when compiling in release mode.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
207
Language Basics
#ifdef __MQL5__
#ifdef _DEBUG
Print("Hello from MQL5 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL5 compiler [RELEASE]");
#endif
#endif
#else
#ifdef __MQL4__
#ifdef _DEBUG
Print("Hello from MQL4 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL4 compiler [RELEASE]");
#endif
#endif
#endif
#endif
}
208
Language Basics
Object-Oriented Programming
Object-oriented programming (OOP) is programming primarily focused on data, while data and
behavior are being inseparably linked. Data and behavior together constitute a class, while objects are
class instances.
The components of the object-oriented approach are:
Encapsulation and type extensibility
Inheritance
Polymorphism
Overloading
Virtual functions
OOP considers computation as modeling of behavior. The modeled item is the object represented by
computational abstractions. 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 edges. Also we need to regulate the falling speed of shapes, define operations of rotation and shift
of shapes. Moving of shapes on the screen is limited by the well's boundaries, this requirement must
also be modeled. Besides that, filled rows of cubes must be destroyed and achieved points must be
counted.
Thus, this easy-to-understand game requires the creation of several models - shape model, well
model, shape movement model and so on. All these models are abstractions, represented by
calculations in the computer. To describe these models, the concept of Abstract Data Type, ADT (or
complex data type) is used. Strictly speaking, the model of the "shapes" motion in the DOM is not a
data type, but it is a set of operations on the "shape" data type, using the restrictions of the "well"
data type.
Objects are class variables. Object-oriented programming allows you to easily create and use ADT.
Object-oriented programming uses the inheritance mechanism. The benefit of inheritance is in the
fact that it allows obtaining derivative types from data types already defined by a user.
For example, to create Tetris shapes, it's convenient to create a base class Shape first. The other
classes representing all seven possible shape types can be derived on its basis. Behavior of shapes is
defined in the base class, while implementation of behavior of each separate shape is defined in
derivative classes.
In OOP objects are responsible for their behavior. ADT developer should include a code to describe any
behavior that would normally be expected from the corresponding objects. The fact that the object
itself is responsible for its behavior, greatly simplifies the 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 knows how to draw itself, the programmer should send a "draw" message when
using such a shape.
The MQL5 Language is a C++ like, and it also has the encapsulation mechanism for the implementation
of ADT. On the one hand encapsulation combines the internal details of the implementation of a
particular type, and on the other hand it combines externally accessible functions that can influence
objects of this type. Implementation details may be inaccessible for a program that uses this type.
209
Language Basics
The concept of OOP has a set of related concepts, including the following:
Simulation of actions from the real world
User-defined data types
Hiding the implementation details
Possibility of the code reuse through inheritance
Interpretation of function calls during execution
Some of these concepts are rather vague, some are abstract, others are general.
210
Language Basics
Example:
class CPerson
{
protected:
string
m_name;
// name
public:
void
string
};
This approach offers several advantages. First, by function name we can understand what it does -
211
Language Basics
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 variable in the CPerson class or in any of its derivative classes.
In this case, we'll need just to change the implementation of functions 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
m_name;
// name
};
class CPerson
{
protected:
Name
public:
void
SetName(string n);
string
GetName(){return(m_name.first_name+" "+m_name.last_name);}
private:
string
GetFirstName(string full_name);
string
GetLastName(string full_name);
};
void CPerson::SetName(string n)
{
m_name.first_name=GetFirstName(n);
m_name.last_name=GetLastName(n);
}
string CPerson::GetFirstName(string full_name)
{
int pos=StringFind(full_name," ");
if(pos>0) StringSetCharacter(full_name,pos,0);
return(full_name);
}
string CPerson::GetLastName(string full_name)
{
string ret_string;
int pos=StringFind(full_name," ");
if(pos>0) ret_string=StringSubstr(full_name,pos+1);
else
ret_string=full_name;
return(ret_string);
}
See also
212
Language Basics
Data Types
213
Language Basics
Inheritance
The characteristic feature of OOP is the encouragement of code reuse through inheritance. A new
class is made from the existing, which is called the base class. The derived class uses the members of
the base class, but can also modify and supplement them.
Many types are variations of the existing types. It is often tedious to develop a new code for each of
them. In addition, the new code implies new errors. The derived class inherits the description of the
base class, thus any re-development and re-testing of code is unnecessary. The inheritance
relationships are hierarchical.
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 it is a property of
all inert gases.
Consider an example of the inheritance of geometric shapes. To describe the whole variety of simple
shapes (circle, triangle, rectangle, 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:
//--- The base class Shape
class CShape
{
protected:
int
m_type;
// Shape type
int
m_xpos;
int
m_ypos;
public:
CShape(){m_type=0; m_xpos=0; m_ypos=0;} // constructor
void
void
};
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:
214
Language Basics
//--- The derived class circle
class CCircle : public CShape
{
private:
int
m_radius;
// circle radius
public:
CCircle(){m_type=1;}// constructor, type 1
};
private:
int
m_square_side;
// square side
public:
CSquare(){m_type=2;} // constructor, type 2
};
It should be noted that while object is created the base class constructor is called first, and then the
constructor of the derived class is called. 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 one is as follows:
class class_name :
(public | protected | private) opt
base_class_name
{
class members declaration
};
One of aspects of the derived class is the visibility (openness) of its members successors (heirs). The
public, protected and private keywords are used to indicate the extent, to which members of the base
class will be available for the derived one. The public keyword after a colon in the header of a derived
class indicates that the protected and public members of the base class 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
215
Language Basics
members of the base class, new members are added in a derivative class.
The derived class may include the implementation of member functions, different from the base class.
It has nothing common with an overload, when the meaning of the same function name may be
different for different signatures.
In protected inheritance, public and protected members of base class become protected members of
derived class. In private inheritance, the public and protected members of base class become private
members of the derived class.
In protected and private inheritance, the relation that "the object of a derivative class is object of a
base class" is not true. The protected and private inheritance types are rare, and each of them needs
to be used carefully.
It should be understood that the type of inheritance (public, protected or private) does not affect the
ways of accessing the members of base classes in the hierarchy of inheritance from a derived
class. With any type of inheritance, only base class members declared with public and protected access
specifiers will be available out of the derived classes. Let's consider it in the following example:
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//+------------------------------------------------------------------+
//| Example class with a few access types
//+------------------------------------------------------------------+
class CBaseClass
{
private:
int
protected:
int
//--- The protected method is available from the base class and its derived cl
Member(){return(m_member);}
public:
private:
CBaseClass(){m_member=5;return;};
void
};
//+------------------------------------------------------------------+
//| Derived class with errors
//+------------------------------------------------------------------+
class CDerived: public CBaseClass // specification of public inheritance can be omitted, since it i
{
public:
void Func() // In the derived class, define a function with calls to base class members
{
//--- An attempt to modify a private member of the base class
m_member=0;
Member(0);
// Error, the private method of the base class is not available in derived
216
Language Basics
Print(Member());
// No error, protected method is available from the base class and its der
}
};
In the above example, CBaseClass has only a public method the constructor. Constructors are called
automatically when creating a class object. Therefore, the private member m_member and the
protected methods Member() cannot be called from the outside. But in case of public inheritance, the
Member() method of the base class will be available from the derived classes.
In case of protected inheritance, all the members of the base class with public and protected access
become protected. It means that if public data members and methods of the base class were
accessible from the outside, with protected inheritance they are available only from the classes of the
derived class and its further derivatives.
//+------------------------------------------------------------------+
//| Example class with a few access types
//+------------------------------------------------------------------+
class CBaseMathClass
{
private:
double
public:
void
SetPI(double v){m_Pi=v;return;};
double
GetPI(){return m_Pi;};
public:
PrintFormat("%s",__FUNCTION__);};
};
//+------------------------------------------------------------------+
//| Derived class, in which m_Pi cannot be modified
//+------------------------------------------------------------------+
class CProtectedChildClass: protected CBaseMathClass // Protected inheritance
{
private:
double
public:
m_radius;
//--- Public methods in the derived class
void
double
GetCircleLength(){return GetPI()*m_radius;};
};
//+------------------------------------------------------------------+
//| Script starting function
//+------------------------------------------------------------------+
void OnStart()
{
//--- When creating a derived class, the constructor of the base class will be called automatically
CProtectedChildClass pt;
//--- Specify radius
pt.SetRadius(10);
PrintFormat("Length=%G",pt.GetCircleLength());
//--- If we uncomment the line below, we will get an error at the stage of compilation, since SetPI
// pt.SetPI(3);
217
Language Basics
//--- Now declare a variable of the base class and try to set the Pi constant equal to 10
CBaseMathClass bc;
bc.SetPI(10);
//--- Here is the result
PrintFormat("bc.GetPI()=%G",bc.GetPI());
}
The example shows that methods SetPI() and GetPi() in the base class CBaseMathClass are open and
available for calling from any place of the program. But at the same time, for CProtectedChildClass
which is derived from it these methods can be called only from the methods of the
CProtectedChildClass class or its derived classes.
In case of private inheritance, all the members of the basic class with the public and protected access
become private, and calling them becomes impossible in further inheritance.
MQL5 has no multiple inheritance.
See also
Structures and Classes
218
Language Basics
Polymorphism
Polymorphism is an opportunity for different classes of objects, related through inheritance, to
respond in various ways when calling the same function element. It helps to create a universal
mechanism describing the behavior of not only the base class, but also descendant classes.
Let's continue to develop a base class 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 redefine 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:
//--- Base class
class CShape
{
protected:
int
m_type;
// Shape type
int
m_xpos;
int
m_ypos;
void
CShape(){m_type=0;};
// constructor, type=0
int
public:
virtual
double
};
Now, all of the derived classes have a member function getArea(), which returns a zero value. The
implementation of this function in each descendant will vary.
//--- The derived class Circle
class CCircle : public CShape
{
private:
double
m_radius;
// circle radius
void
CCircle(){m_type=1;};
// constructor, type=1
void
SetRadius(double r){m_radius=r;};
public:
219
Language Basics
private:
double
m_square_side;
// square side
public:
void
void
SetSide(double s){m_square_side=s;};
virtual double
};
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];
220
Language Basics
221
Language Basics
Please note that when deleting an object using the delete operator, the type of its pointer must be
checked. Only objects with the POINTER_DYNAMIC pointer can be deleted using delete. For pointers of
other type, an error will be returned.
But besides the redefining of functions during inheritance, polymorphism also includes the
implementation of one and the same functions with different sets of parameters within a class. This
means that the class may have several functions with the same name but with a different type and/or
set of parameters. In this case, polymorphism is implemented through the function overload.
See also
Standard Library
222
Language Basics
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.
Method overloading is one of ways of polymorphism realization. Overloading of methods is performed
according to the same rules as the function overloading.
If the called function has no exact match, the compiler searches for a suitable function on three levels
sequentially:
1. search within class methods.
2. search within the base class methods, consistently from the nearest ancestor to the very first.
3. search among other functions.
If there is no exact correspondence at all levels, but several suitable functions at different levels have
been found, the function found at the least level is used. Within one level, there can't be more than
one suitable function.
See also
Function Overloading
223
Language Basics
Virtual Functions
The virtual keyword is the function specifier, which provides a mechanism to select dynamically at
runtime an appropriate function-member among the functions of basic and derived classes. 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
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()
virtual void
Draw()
{ return;
224
Language Basics
virtual bool
CheckDown(int& pad_array[]);
virtual bool
CheckLeft(int& side_row[]);
virtual bool
CheckRight(int& side_row[]);
};
Further, for each derived class, this function is implemented in accordance with characteristics of a
descendant class. For example, the first shape CTetrisShape1 has its own implementation of the
Draw() function:
class CTetrisShape1 : public CTetrisShape
{
public:
//--- shape drawing
virtual void
Draw()
{
int
i;
string name;
//--if(m_turn==0 || m_turn==2)
{
//--- horizontal
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+i*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos);
}
}
else
{
//--- vertical
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos+i*SHAPE_SIZE);
}
}
}
}
The Square shape is described by class CTetrisShape6 and has its own implementation of the Draw()
method:
class CTetrisShape6 : public CTetrisShape
{
public:
//--- Shape drawing
virtual void
Draw()
225
Language Basics
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
226
Language Basics
where class_name is the name of the class, and variable is the name of the class member.
As you see, to access the static member of a class, context resolution operator :: is used. When you
access a static member within class methods, the context operator is optional.
Static member of a class has to be explicitly initialized with desired value. For this it must be declared
and initialized in global scope. The sequence of static members initialization will correspond to the
sequence of their declaration in global scope.
For example, we have a class CParser used for parsing the text, and we need to count the total
number of processed words and characters. We only need to declare the necessary class members as
static and initialize them at the global level. Then all instances of the class will use common counters
of words and characters.
//+------------------------------------------------------------------+
//| Class "Text analyzer"
//+------------------------------------------------------------------+
class CParser
{
public:
static int
s_words;
static int
s_symbols;
A static class member can be declared with the const keyword. Such static constants must be
initialized at the global level with the const keyword:
227
Language Basics
//+------------------------------------------------------------------+
//| Class "Stack" for storing processed data
//+------------------------------------------------------------------+
class CStack
{
public:
CStack(void);
~CStack(void){};
...
private:
static const int
};
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;
Pointer this
The keyword this denotes an implicitly declared pointer to itself to a specific instance of the class, in
the context of which the method is executed. It can be used only in non-static methods of the class.
Pointer this is an implicit non-static member of any class.
In static functions you can access only static members/methods of a class.
Static Methods
In MQL5 member functions of type static can be used. The static modifier must precede the return
type of a function in the declaration inside a class.
class CStack
{
public:
//--- Constructor and destructor
CStack(void){};
~CStack(void){};
//--- Maximum stack capacity
static int
Capacity();
private:
int
m_length;
};
//+------------------------------------------------------------------+
//| Returns the maximum number of elements to store in the stack
//+------------------------------------------------------------------+
int CStack::Capacity(void)
{
return(s_max_length);
}
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;
228
Language Basics
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare CStack type variable
CStack stack;
//--- call the object's static method
Print("CStack.s_max_length=",stack.Capacity());
//--- it can also be called the following way, as the method is static and does not require the pre
Print("CStack.s_max_length=",CStack::Capacity());
}
A method with the const modifier is called constant and cannot modify implicit members of its class.
Declaration of constant functions of a class and constant parameters is called const-correctness
control. Through this control you can be sure that the compiler will ensure the consistency of values of
objects and will return an error during compilation if there is something wrong.
The const modifier is placed after the list of arguments inside a class declaration. Definition outside a
class should also include the const modifier:
//+------------------------------------------------------------------+
//| Class "Rectangle"
//+------------------------------------------------------------------+
class CRectangle
{
private:
double
m_width;
// Width
double
m_height;
// Height
public:
//--- Constructors and destructor
CRectangle(void):m_width(0),m_height(0){};
CRectangle(const double w,const double h):m_width(w),m_height(h){};
~CRectangle(void){};
//--- Calculating the area
double
Square(void) const;
static double
};
//+------------------------------------------------------------------+
//| Returns the area of the "Rectangle" object
//+------------------------------------------------------------------+
double CRectangle::Square(void) const
{
return(Square(m_width,m_height));
}
//+------------------------------------------------------------------+
//| Returns the product of two variables
//+------------------------------------------------------------------+
static double CRectangle::Square(const double w,const double h)
{
229
Language Basics
return(w*h);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Create a rectangle rect with the sides equal to 5 and 6
CRectangle rect(5,6);
//--- Find the rectangle area using a constant method
PrintFormat("rect.Square()=%.2f",rect.Square());
//--- Find the product of numbers using the static method of class CRectangle
PrintFormat("CRectangle::Square(2.0,1.5)=%f",CRectangle::Square(2.0,1.5));
}
An additional argument in favor of using the constancy control is the fact that in this case, the
compiler generates a special optimization, for example, places a constant object in read-only memory.
A static function cannot be determined with the const modifier, because this modifier ensures the
constancy of the instance members when calling this function. But, as mentioned above, the static
function cannot access non-static class members.
See also
Static Variables, Variables, References. Modifier & and Keyword this
230
Language Basics
Function templates
Overloaded functions are commonly used to perform similar operations on various data types.
ArraySize() is a simple example of such function in MQL5. It returns size of any type of array. In fact,
this system function is overloaded and the entire implementation of such an overload is hidden from
MQL5 application developers:
int ArraySize(
void& array[]
// checked array
);
It means that MQL5 language compiler inserts necessary implementation for each call of this function.
For example, that is how it can be done for integer type arrays:
int ArraySize(
int& array[]
);
ArraySize() function can be displayed the following way for MqlRates type array for working with
quotations in historical data format:
int ArraySize(
MqlRates& array[]// array filled with MqlRates type values
);
Thus, it is very convenient to use the same function for working with different types. However, all
preliminary work should be carried out the necessary function should be overloaded for all data types
it should correctly work with.
There is a convenient solution. If similar operations should be executed for each data type, it is
possible to use function templates. In this case, a programmer needs to write only one function
template description. When describing the template in such a way, we should specify only some formal
parameter instead of some definite data type the function should work with. The compiler will
automatically generate various functions for the appropriate handling of each type based on the types
of the arguments used when calling the function.
Function template definition starts with the template keyword followed by the list of formal
parameters in angle brackets. Each formal parameter is preceded by the typename keyword. Formal
parameter types are built-in or user-defined types. They are used:
to specify the types of function arguments,
to specify the types of function's return value,
to declare the variables inside the function definition
Number of template parameters cannot exceed eight. Each formal parameter in the template
definition should appear in the list of function parameters at least once. Each name of the formal
parameter should be unique.
Below is an example of a function template for searching the highest value in the array of any numeric
type (integer and real numbers):
231
Language Basics
template<typename T>
T ArrayMax(T &arr[])
{
uint size=ArraySize(arr);
if(size==0) return(0);
T max=arr[0];
for(uint n=1;n<size;n++)
if(max<arr[n]) max=arr[n];
//--return(max);
}
This template defines the function that finds the highest value in the passed array and returns this
value as a result. Keep in mind that the ArrayMaximum() function built in MQL5 returns only the
highest value index that can be used to find the value itself. For example:
//--- create an array
double array[];
int size=50;
ArrayResize(array,size);
//---
for(int i=0;i<size;i++)
{
array[i]=MathRand();
}
//--- find position of the highest value in the array
int max_position=ArrayMaximum(array);
//--- now, get the highest value itself in the array
double max=array[max_position];
//--- display the found value
Print("Max value = ",max);
Thus, we have performed two steps to get the highest value in the array. With ArrayMax() function
template, we can get the result of the necessary type just by passing the array of an appropriate type
into this function. It means that instead of two last lines
//--- find position of the highest value in the array
int max_position=ArrayMaximum(array);
//--- now, get the highest value itself in the array
double max=array[max_position];
we now can use only one line, in which the returned result has the same type as the array passed into
function:
//--- find the highest value
double max=ArrayMax(array);
In this case, the type of result returned by the ArrayMax() function will automatically match the type of
array.
232
Language Basics
Use the typename keyword to get the argument type as a string in order to create general purpose
methods of working with various data types. Let's consider a specific example of the function that
returns data type as a string:
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void OnStart()
{
//--CTrade trade;
double d_value=M_PI;
int i_value=INT_MAX;
Print("d_value: type=",GetTypeName(d_value), ",
value=", d_value);
value=", i_value);
Print("trade: type=",GetTypeName(trade));
//--}
//+------------------------------------------------------------------+
//| Type is returned as a line
//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T &t)
{
//--- return the type as a line
return(typename(T));
//--}
Function templates can also be used for class methods, for example:
class CFile
{
...
public:
...
template<typename T>
uint WriteStruct(T &data);
};
template<typename T>
uint CFile::WriteStruct(T &data)
{
...
return(FileWriteStruct(m_handle,data));
}
233
Language Basics
Function templates should not be declared with export, virtual and #import keywords.
234
Language Basics
CAnimal();
// Constructor
Sound() = 0;
m_legs_count;
private:
double
};
Here Sound() is a pure virtual function, because it is declared with the specifier of the pure virtual
function PURE (=0).
Pure virtual functions are only the virtual functions for which the PURE specifier is set: (=NULL) or
(=0). Example of abstract class declaration and use:
class CAnimal
{
public:
virtual void
Sound()=NULL;
};
//--- Derived from an abstract class
class CCat : public CAnimal
{
public:
virtual void
};
//--- Examples of wrong use
new CAnimal;
CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract
//--- Examples of proper use
new CCat;
CCat cat;
235
Language Basics
//+------------------------------------------------------------------+
class CAnimal
{
public:
//--- A pure virtual function
virtual void
Sound(void)=NULL;
//--- Function
void
CallSound(void) { Sound(); }
//--- Constructor
CAnimal()
{
//--- An explicit call of the virtual method
Sound();
//--- An implicit call (using a third function)
CallSound();
//--- A constructor and/or destructor always calls its own functions,
//--- even if they are virtual and overridden by a called function in a derived class
//--- If the called function is pure virtual,
//--- its call will cause a critical runtime error: "pure virtual function call"
}
};
However, constructors and destructors for abstract classes can call other member functions.
236
charts;
Indicators constants are used for working with standard and custom indicators;
Environment state constants describe properties of a MQL5-program, show information about a
requests;
In/out constants are designed for working with file functions and displaying messages on the screen
237
Chart Constants
Constants describing various properties of charts are divided into the following groups:
Types of events events that occur when working with charts;
Chart timeframes standard built-in periods;
Properties of chart identifiers that are used as parameters of chart functions;
Positioning constants - value of a parameter of the ChartNavigate() function;
Displaying charts - setting the chart appearance.
238
Description
CHARTEVENT_KEYDOWN
Keystrokes
CHARTEVENT_MOUSE_MOVE
Mouse
move,
mouse
clicks
(if
CHART_EVENT_MOUSE_MOVE=true is set for the
chart)
CHARTEVENT_OBJECT_CREATE
Graphical
object
created
(if
CHART_EVENT_OBJECT_CREATE=true is set for
the chart)
CHARTEVENT_OBJECT_CHANGE
CHARTEVENT_OBJECT_DELETE
Graphical
object
deleted
(if
CHART_EVENT_OBJECT_DELETE=true is set for
the chart)
CHARTEVENT_CLICK
Clicking on a chart
CHARTEVENT_OBJECT_CLICK
CHARTEVENT_OBJECT_DRAG
CHARTEVENT_OBJECT_ENDEDIT
CHARTEVENT_CHART_CHANGE
CHARTEVENT_CUSTOM
CHARTEVENT_CUSTOM_LAST
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.
Event
Event
of
keystroke
Value of the id
parameter
Value of
lparam
parameter
the
CHARTEVENT_KE
YDOWN
code
of
pressed key
Value of
dparam
parameter
the
Repeat
count
(the number of
Value of
sparam
parameter
the
239
times
the
keystroke
is
repeated as a
result of the user
holding down the
key)
describing
the
status
of
keyboard buttons
CHARTEVENT_MO
USE_MOVE
the X coordinate
the Y coordinate
event
of
graphical object
creation
(if
CHART_EVENT_O
BJECT_CREATE=t
rue is set for the
chart)
CHARTEVENT_OB
JECT_CREATE
Name of the
created graphical
object
Event of change
of an object
property via the
properties dialog
CHARTEVENT_OB
JECT_CHANGE
Name of the
modified
graphical object
Event
of
graphical object
deletion
(if
CHART_EVENT_O
BJECT_DELETE=t
rue is set for the
chart)
CHARTEVENT_OB
JECT_DELETE
Name of the
deleted graphical
object
Event
of
a
mouse click on
the chart
CHARTEVENT_C
LICK
the X coordinate
the Y coordinate
Event
of
a
mouse click in a
graphical object
belonging to the
chart
CHARTEVENT_OB
JECT_CLICK
the X coordinate
the Y coordinate
Name of the
graphical object,
on which the
event occurred
Event
of
a
graphical object
dragging using
the mouse
CHARTEVENT_OB
JECT_DRAG
Name of the
moved graphical
object
Event of the
finished
text
editing in the
entry box of the
LabelEdit
CHARTEVENT_OB
JECT_ENDEDIT
Name of the
LabelEdit
graphical object,
in which text
editing
has
240
graphical object
completed
Event of change
of the chart size
or modification
of
chart
properties
through
the
Properties dialog
CHARTEVENT_C
HART_CHANGE
ID of the user
event under the
N number
CHARTEVENT_CU
STOM+N
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
104
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--Print("The expert with name ",MQL5InfoString(MQL5_PROGRAM_NAME)," is running");
//--- enable object create events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_CREATE,true);
//--- enable object delete events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_DELETE,true);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| ChartEvent function
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long& lparam,
// Event identifier
// Event parameter of long type
)
{
//--- the left mouse button has been pressed on the chart
241
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:
break;
case KEY_LEFT:
break;
case KEY_NUMLOCK_UP:
break;
case KEY_UP:
break;
break;
case KEY_RIGHT:
break;
case KEY_NUMLOCK_DOWN:
break;
case KEY_DOWN:
break;
case KEY_NUMPAD_5:
break;
case KEY_NUMLOCK_5:
break;
default:
}
ChartRedraw();
}
//--- the object has been deleted
if(id==CHARTEVENT_OBJECT_DELETE)
{
Print("The object with name ",sparam," has been deleted");
}
//--- the object has been created
if(id==CHARTEVENT_OBJECT_CREATE)
{
Print("The object with name ",sparam," has been created");
}
//--- the object has been moved or its anchor point coordinates has been changed
if(id==CHARTEVENT_OBJECT_DRAG)
{
Print("The anchor point coordinates of the object with name ",sparam," has been changed");
}
//--- the text in the Edit of object has been changed
if(id==CHARTEVENT_OBJECT_ENDEDIT)
{
Print("The text in the Edit field of the object with name ",sparam," has been changed");
}
}
242
Description
1
Example:
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
void OnInit()
{
//--- enable CHART_EVENT_MOUSE_MOVE messages
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,1);
}
//+------------------------------------------------------------------+
//| MouseState
//+------------------------------------------------------------------+
string MouseState(uint state)
{
string res;
res+="\nML: "
// mouse left
res+="\nMR: "
// mouse right
res+="\nMM: "
+(((state&16)==16)?"DN":"UP");
// mouse middle
res+="\nMX: "
+(((state&32)==32)?"DN":"UP");
res+="\nMY: "
+(((state&64)==64)?"DN":"UP");
// shift key
// control key
return(res);
}
//+------------------------------------------------------------------+
//| ChartEvent function
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
if(id==CHARTEVENT_MOUSE_MOVE)
Comment("POINT: ",(int)lparam,",",(int)dparam,"\n",MouseState((uint)sparam));
}
243
See also
Event Handling Functions, Working with events
244
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_CURRENT
Current timeframe
PERIOD_M1
1 minute
PERIOD_M2
2 minutes
PERIOD_M3
3 minutes
PERIOD_M4
4 minutes
PERIOD_M5
5 minutes
PERIOD_M6
6 minutes
PERIOD_M10
10 minutes
PERIOD_M12
12 minutes
PERIOD_M15
15 minutes
PERIOD_M20
20 minutes
PERIOD_M30
30 minutes
PERIOD_H1
1 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);
245
See also
PeriodSeconds, Period, Date and Time, Visibility of objects
246
Chart Properties
Identifiers of ENUM_CHART_PROPERTY enumerations are used as parameters of functions for working
with charts. The abbreviation of r/o in the "Property Type" column means that this property is readonly and cannot be changed. The w/o abbreviation in the "Property Type" column means that this
property is write-only and it cannot be received. 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.
The functions defining the chart properties are actually used for sending change commands to the
chart. If these functions are executed successfully, the command is included in the common queue of
the chart events. The changes are implemented to the chart when handling the queue of the chart
events.
Thus, do not expect an immediate visual update of the chart after calling these functions. Generally,
the chart is updated automatically by the terminal following the change events - a new quote arrival,
resizing the chart window, etc. Use ChartRedraw() function to forcefully update the chart.
For functions ChartSetInteger() and ChartGetInteger()
ENUM_CHART_PROPERTY_INTEGER
ID
Description
Property Type
CHART_IS_OBJECT
Identifying
"Chart" (OBJ_CHART) object
returns true for a graphical
object. Returns false for a real
chart
bool r/o
CHART_BRING_TO_TOP
bool w/o
CHART_MOUSE_SCROLL
bool
CHART_EVENT_MOUSE_MOVE
bool
CHART_EVENT_OBJECT_CREAT
E
bool
CHART_EVENT_OBJECT_DELET
bool
247
of
object
deletion
(CHARTEVENT_OBJECT_DELETE
) to all mql5-programs on a
chart
CHART_MODE
enum
CHART_FOREGROUND
bool
CHART_SHIFT
bool
CHART_AUTOSCROLL
bool
CHART_SCALE
Scale
int
CHART_SCALEFIX
bool
CHART_SCALEFIX_11
bool
CHART_SCALE_PT_PER_BAR
bool
CHART_SHOW_OHLC
bool
CHART_SHOW_BID_LINE
bool
CHART_SHOW_ASK_LINE
bool
CHART_SHOW_LAST_LINE
bool
CHART_SHOW_PERIOD_SEP
bool
CHART_SHOW_GRID
bool
CHART_SHOW_VOLUMES
enum
ENUM_CHART_VOLUME_MODE
CHART_SHOW_OBJECT_DESCR
bool
CHART_VISIBLE_BARS
int r/o
CHART_WINDOWS_TOTAL
int r/o
CHART_WINDOW_IS_VISIBLE
Visibility of subwindows
ENUM_CHART_MODE
from 0 to 5
248
CHART_WINDOW_HANDLE
int r/o
CHART_WINDOW_YDISTANCE
int r/o
number
CHART_FIRST_VISIBLE_BAR
int r/o
CHART_WIDTH_IN_BARS
int r/o
CHART_WIDTH_IN_PIXELS
int r/o
CHART_HEIGHT_IN_PIXELS
int
modifier - subwindow
number
CHART_COLOR_BACKGROUND
color
CHART_COLOR_FOREGROUND
color
CHART_COLOR_GRID
Grid color
color
CHART_COLOR_VOLUME
color
CHART_COLOR_CHART_UP
color
CHART_COLOR_CHART_DOWN
color
modifier - subwindow
249
bear candlesticks
CHART_COLOR_CHART_LINE
color
CHART_COLOR_CANDLE_BULL
color
CHART_COLOR_CANDLE_BEAR
color
CHART_COLOR_BID
color
CHART_COLOR_ASK
color
CHART_COLOR_LAST
color
CHART_COLOR_STOP_LEVEL
color
CHART_SHOW_TRADE_LEVELS
bool
CHART_DRAG_TRADE_LEVELS
bool
CHART_SHOW_DATE_SCALE
bool
CHART_SHOW_PRICE_SCALE
bool
CHART_SHOW_ONE_CLICK
bool
Description
Property Type
CHART_SHIFT_SIZE
double
(from
percents)
CHART_FIXED_POSITION
double
10
to
50
250
double
CHART_FIXED_MIN
double
CHART_POINTS_PER_BAR
double
CHART_PRICE_MIN
Chart minimum
double r/o
modifier
subwindow number
CHART_PRICE_MAX
Chart maximum
double r/o
modifier
subwindow number
Description
CHART_COMMENT
Property Type
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);
251
See also
Examples of Working with the Chart
252
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
CHART_BEGIN
CHART_CURRENT_POS
Current position
CHART_END
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();
}
253
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
CHART_BARS
CHART_CANDLES
CHART_LINE
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
CHART_VOLUME_HIDE
CHART_VOLUME_TICK
Tick volumes
CHART_VOLUME_REAL
Trade volumes
Example:
//--- Get the handle of the current chart
long handle=ChartID();
if(handle>0) // If it succeeded, additionally customize
{
//--- Disable autoscroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- Set the indent of the right border of the chart
ChartSetInteger(handle,CHART_SHIFT,true);
//--- Display as candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- Scroll by 100 bars from the beginning of history
ChartNavigate(handle,CHART_CURRENT_POS,100);
//--- Set the tick volume display mode
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
254
See also
ChartOpen, ChartID
255
//+------------------------------------------------------------------+
//| Checks if an object is a chart. If it is a graphic object,
//+------------------------------------------------------------------+
bool ChartIsObject(bool &result,const long chart_ID=0)
{
256
//+----------------------------------------------------------------------+
//| Sends command to the terminal to display the chart above all others
//+----------------------------------------------------------------------+
bool ChartBringToTop(const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- show the chart on top of all others
if(!ChartSetInteger(chart_ID,CHART_BRING_TO_TOP,0,true))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_MOUSE_SCROLL is a property for scrolling the chart using left mouse button.
//+--------------------------------------------------------------------------+
//| Checks if scrolling of chart using left mouse button is enabled
//+--------------------------------------------------------------------------+
bool ChartMouseScrollGet(bool &result,const long chart_ID=0)
{
257
//+--------------------------------------------------------------------+
bool ChartMouseScrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MOUSE_SCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_EVENT_MOUSE_MOVE
//+------------------------------------------------------------------+
//| Checks if messages concerning move events and mouse clicks
//+------------------------------------------------------------------+
bool ChartEventMouseMoveGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
258
//+------------------------------------------------------------------------------+
bool ChartEventMouseMoveSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//| object creation are sent to all MQL5 applications on the chart
//+---------------------------------------------------------------------+
bool ChartEventObjectCreateGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
259
//+--------------------------------------------------------------------------+
bool ChartEventObjectCreateSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+---------------------------------------------------------------------+
bool ChartEventObjectDeleteGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
260
//+--------------------------------------------------------------------------+
bool ChartEventObjectDeleteSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets chart display type (candlesticks, bars or line)
//+------------------------------------------------------------------+
ENUM_CHART_MODE ChartModeGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MODE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((ENUM_CHART_MODE)result);
}
//+------------------------------------------------------------------+
//| Sets chart display type (candlesticks, bars or line)
//+------------------------------------------------------------------+
bool ChartModeSet(const long value,const long chart_ID=0)
{
//--- reset the error value
261
//+------------------------------------------------------------------+
//| Checks if a price chart is displayed in the foreground
//+------------------------------------------------------------------+
bool ChartForegroundGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of a price chart on the foreground
//+------------------------------------------------------------------+
bool ChartForegroundSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
262
CHART_SHIFT mode of shift of the price chart from the right border.
//+-------------------------------------------------------------------+
//| Checks if shifting a price chart from the right border is enabled |
//+-------------------------------------------------------------------+
bool ChartShiftGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+---------------------------------------------------------------------------------+
//| Enables/disables displaying of a price chart with a shift from the right border |
//+---------------------------------------------------------------------------------+
bool ChartShiftSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
263
//+------------------------------------------------------------------+
//| Checks if automatic scrolling of a chart to the right
//+------------------------------------------------------------------+
bool ChartAutoscrollGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables automatic scrolling of a chart to the right
//+------------------------------------------------------------------+
bool ChartAutoscrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
264
//+------------------------------------------------------------------+
int ChartScaleGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Sets chart scale (from 0 to 5)
//+------------------------------------------------------------------+
bool ChartScaleSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Checks if the fixed scale mode is enabled
//+------------------------------------------------------------------+
bool ChartScaleFixGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
265
//+------------------------------------------------------------------+
bool ChartScaleFixSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Checks if the "1:1" scale is enabled
//+------------------------------------------------------------------+
bool ChartScaleFix11Get(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
266
//+------------------------------------------------------------------+
bool ChartScaleFix11Set(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SCALE_PT_PER_BAR the mode of specifying the chart scale in points per bar.
//+------------------------------------------------------------------+
//| Checks if the "points per bar" chart scaling mode is enabled
//+------------------------------------------------------------------+
bool ChartScalePerBarGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables the "points per bar" chart scaling mode
//+------------------------------------------------------------------+
267
CHART_SHOW_OHLC the property of displaying OHLC values in the upper left corner.
//+----------------------------------------------------------------------------------+
//| Checks if displaying of OHLC values in the upper left corner of chart is enabled |
//+----------------------------------------------------------------------------------+
bool ChartShowOHLCGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------------------+
//| Enables/disables displaying of OHLC values in the upper left corner of chart |
//+------------------------------------------------------------------------------+
bool ChartShowOHLCSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
268
CHART_SHOW_BID_LINE the property of displaying Bid value as a horizontal line on the chart.
//+------------------------------------------------------------------+
//| Checks if displaying of Bid line on chart is enabled
//+------------------------------------------------------------------+
bool ChartShowBidLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of Bid line on chart
//+------------------------------------------------------------------+
bool ChartShowBidLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
269
//+------------------------------------------------------------------+
//| Checks if displaying of Ask line on chart is enabled
//+------------------------------------------------------------------+
bool ChartShowAskLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of Ask line on chart
//+------------------------------------------------------------------+
bool ChartShowAskLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-----------------------------------------------------------------------------+
//| Checks if displaying of line for the last performed deal's price is enabled |
//+-----------------------------------------------------------------------------+
270
periods.
//+---------------------------------------------------------------------------------+
//| Checks if displaying of vertical separators between adjacent periods is enabled |
//+---------------------------------------------------------------------------------+
bool ChartShowPeriodSeparatorGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
271
//+------------------------------------------------------------------+
//| Checks if the chart grid is displayed
//+------------------------------------------------------------------+
bool ChartShowGridGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
272
//+------------------------------------------------------------------+
bool ChartShowGridSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Checks if volumes are displayed on a chart
//+------------------------------------------------------------------+
ENUM_CHART_VOLUME_MODE ChartShowVolumesGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_VOLUMES,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((ENUM_CHART_VOLUME_MODE)result);
}
//+------------------------------------------------------------------+
//| Sets mode of displaying volumes on chart
//+------------------------------------------------------------------+
bool ChartShowVolumesSet(const long value,const long chart_ID=0)
273
//+-------------------------------------------------------------------+
//| Checks if pop-up descriptions of graphical objects are displayed
//+-------------------------------------------------------------------+
bool ChartShowObjectDescriptionGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Enables/disables displaying of pop-up descriptions of graphical objects |
//| when hovering mouse over them
//+-------------------------------------------------------------------------+
bool ChartShowObjectDescriptionSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
274
CHART_VISIBLE_BARS defines the number of bars on a chart that are available for display.
//+----------------------------------------------------------------------+
//| Gets the number of bars that are displayed (visible) in chart window |
//+----------------------------------------------------------------------+
int ChartVisibleBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_VISIBLE_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WINDOWS_TOTAL defines
subwindows.
//+-----------------------------------------------------------------------+
//| Gets the total number of chart windows including indicator subwindows |
//+-----------------------------------------------------------------------+
int ChartWindowsTotal(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOWS_TOTAL,0,result))
{
275
//+------------------------------------------------------------------+
//| Checks if the current chart window or subwindow is visible
//+------------------------------------------------------------------+
bool ChartWindowsIsVisible(bool &result,const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_IS_VISIBLE,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the chart handle
//+------------------------------------------------------------------+
int ChartWindowsHandle(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_HANDLE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
276
CHART_WINDOW_YDISTANCE defines the distance in pixels between the upper frame of the
indicator subwindow and the upper frame of the chart's main window.
//+------------------------------------------------------------------+
//| Gets the distance in pixels between the upper border of
//+------------------------------------------------------------------+
int ChartWindowsYDistance(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_YDISTANCE,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_FIRST_VISIBLE_BAR returns the number of the first visible bar on the chart (bar indexing
//| Indexing is performed like in timeseries: latest bars have smallest indices. |
//+------------------------------------------------------------------------------+
int ChartFirstVisibleBar(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_FIRST_VISIBLE_BAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
277
//+------------------------------------------------------------------+
//| Gets the width of chart (in bars)
//+------------------------------------------------------------------+
int ChartWidthInBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Gets the width of chart (in pixels)
//+------------------------------------------------------------------+
int ChartWidthInPixels(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_PIXELS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
278
//+------------------------------------------------------------------+
//| Gets the height of chart (in pixels)
//+------------------------------------------------------------------+
int ChartHeightInPixelsGet(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Sets the height of chart (in pixels)
//+------------------------------------------------------------------+
bool ChartHeightInPixelsSet(const int value,const long chart_ID=0,const int sub_window=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the background color of chart
//+------------------------------------------------------------------+
color ChartBackColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
279
//+------------------------------------------------------------------+
bool ChartBackColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the chart background color
if(!ChartSetInteger(chart_ID,CHART_COLOR_BACKGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the color of axes, scale and OHLC line
//+------------------------------------------------------------------+
color ChartForeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of axes, scale and OHLC line
if(!ChartGetInteger(chart_ID,CHART_COLOR_FOREGROUND,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
280
//+------------------------------------------------------------------+
bool ChartForeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of axes, scale and OHLC line
if(!ChartSetInteger(chart_ID,CHART_COLOR_FOREGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the color of chart grid
//+------------------------------------------------------------------+
color ChartGridColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive chart grid color
if(!ChartGetInteger(chart_ID,CHART_COLOR_GRID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of chart grid
//+------------------------------------------------------------------+
bool ChartGridColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set chart grid color
if(!ChartSetInteger(chart_ID,CHART_COLOR_GRID,clr))
{
281
//+------------------------------------------------------------------+
//| Gets the color of volumes and market entry levels
//+------------------------------------------------------------------+
color ChartVolumeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of volumes and market entry levels
if(!ChartGetInteger(chart_ID,CHART_COLOR_VOLUME,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of volumes and market entry levels
//+------------------------------------------------------------------+
bool ChartVolumeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of volumes and market entry levels
if(!ChartSetInteger(chart_ID,CHART_COLOR_VOLUME,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
282
//+-----------------------------------------------------------------------------+
//| Gets the color of up bar, shadow and border of a bullish candlestick's body |
//+-----------------------------------------------------------------------------+
color ChartUpColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of up bar, its shadow and border of bullish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_UP,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of up bar, shadow and border of a bullish candlestick's body |
//+------------------------------------------------------------------+
bool ChartUpColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of up bar, its shadow and border of body of a bullish candlestick
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_UP,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CHART_DOWN color of down bar, its shadow and border of bearish candlestick's
body.
//+-------------------------------------------------------------------------------+
//| Gets the color of down bar, shadow and border of a bearish candlestick's body |
//+-------------------------------------------------------------------------------+
color ChartDownColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
283
//+------------------------------------------------------------------+
//| Gets the color of chart line and Doji candlesticks
//+------------------------------------------------------------------+
color ChartLineColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the chart line and Doji candlesticks
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_LINE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
284
//+------------------------------------------------------------------+
bool ChartLineColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the chart line and Doji candlesticks
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_LINE,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the color of bullish candlestick's body
//+------------------------------------------------------------------+
color ChartBullColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bullish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of bullish candlestick's body
//+------------------------------------------------------------------+
bool ChartBullColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of bullish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,clr))
285
//+------------------------------------------------------------------+
//| Gets the color of bearish candlestick's body
//+------------------------------------------------------------------+
color ChartBearColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bearish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of bearish candlestick's body
//+------------------------------------------------------------------+
bool ChartBearColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
286
//+------------------------------------------------------------------+
//| Gets the color of Bid line
//+------------------------------------------------------------------+
color ChartBidColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of Bid price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_BID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of Bid line
//+------------------------------------------------------------------+
bool ChartBidColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Bid price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_BID,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the color of Ask line
//+------------------------------------------------------------------+
color ChartAskColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
287
//+------------------------------------------------------------------+
bool ChartAskColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Ask price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_ASK,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the color of the last performed deal's price line
//+------------------------------------------------------------------+
color ChartLastColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the last performed deal's price line (Last)
if(!ChartGetInteger(chart_ID,CHART_COLOR_LAST,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
288
//+------------------------------------------------------------------+
bool ChartLastColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the last performed deal's price line (Last)
if(!ChartSetInteger(chart_ID,CHART_COLOR_LAST,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_STOP_LEVEL stop order level color (Stop Loss and Take Profit).
//+------------------------------------------------------------------+
//| Gets the color of Stop Loss and Take Profit levels
//+------------------------------------------------------------------+
color ChartStopLevelColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of stop order levels (Stop Loss and Take Profit)
if(!ChartGetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of Stop Loss and Take Profit levels
//+------------------------------------------------------------------+
bool ChartStopLevelColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of stop order levels (Stop Loss and Take Profit)
if(!ChartSetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,clr))
{
289
//+------------------------------------------------------------------+
bool ChartShowTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of trading levels
//+------------------------------------------------------------------+
bool ChartShowTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
290
using mouse.
//+----------------------------------------------------------------------+
//| Checks if dragging of trading levels on chart using mouse is allowed |
//+----------------------------------------------------------------------+
bool ChartDragTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables dragging of trading levels on chart using mouse |
//+------------------------------------------------------------------+
bool ChartDragTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
291
//+------------------------------------------------------------------+
bool ChartShowDateScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of the time scale on chart
//+------------------------------------------------------------------+
bool ChartShowDateScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Checks if the price scale is displayed on chart
//+------------------------------------------------------------------+
bool ChartShowPriceScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
292
//+------------------------------------------------------------------+
bool ChartShowPriceScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PRICE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Checks if the "One click trading" panel is displayed on chart
//+------------------------------------------------------------------+
bool ChartShowOneClickPanelGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_ONE_CLICK,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
293
//| on chart
//+------------------------------------------------------------------+
bool ChartShowOneClickPanelSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_ONE_CLICK,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHIFT_SIZE shift size of the zero bar from the right border in percentage values.
//+-----------------------------------------------------------------+
//| Gets the size of shifting of the zero bar from the right border |
//| of the chart in percentage values (from 10% up to 50%)
//+-----------------------------------------------------------------+
double ChartShiftSizeGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_SHIFT_SIZE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+-----------------------------------------------------------------------------+
//| Gets the size of shifting of the zero bar from the right border
294
//| To enable the shift mode, CHART_SHIFT property value should be set to true. |
//+-----------------------------------------------------------------------------+
bool ChartShiftSizeSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_SHIFT_SIZE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_FIXED_POSITION chart fixed position from the left border in percentage value.
//+----------------------------------------------------------------------------------------+
//| Gets the location of chart's fixed position from the left border (in percentage value) |
//+----------------------------------------------------------------------------------------+
double ChartFixedPositionGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_POSITION,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+-----------------------------------------------------------------------------------------+
//| Gets the location of chart's fixed position from the left border (in percentage value). |
//| To view the location of chart's fixed position, the value of CHART_AUTOSCROLL property
//+-----------------------------------------------------------------------------------------+
bool ChartFixedPositionSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
295
//+------------------------------------------------------------------+
//| Gets the value of chart's fixed maximum
//+------------------------------------------------------------------+
double ChartFixedMaxGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MAX,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| Sets the value of chart's fixed maximum.
//+------------------------------------------------------------------+
bool ChartFixedMaxSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MAX,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
296
//+------------------------------------------------------------------+
//| Gets the value of chart's fixed minimum
//+------------------------------------------------------------------+
double ChartFixedMinGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MIN,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| Sets the value of chart's fixed minimum.
//+------------------------------------------------------------------+
bool ChartFixedMinSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MIN,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets the value of chart scale in points per bar
//+------------------------------------------------------------------+
297
//| To view the result of this property's value change, the value of
//+----------------------------------------------------------------------+
//| Gets the value of chart minimum in the main window or in a subwindow |
//+----------------------------------------------------------------------+
double ChartPriceMin(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MIN,sub_window,result))
298
//+----------------------------------------------------------------------+
//| Gets the value of chart maximum in the main window or in a subwindow |
//+----------------------------------------------------------------------+
double ChartPriceMax(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MAX,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| Gets comment in the upper left corner of chart
//+------------------------------------------------------------------+
bool ChartCommentGet(string &result,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetString(chart_ID,CHART_COMMENT,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
299
//+------------------------------------------------------------------+
bool ChartCommentSet(const string str,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetString(chart_ID,CHART_COMMENT,str))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
10
#define X_PROPERTY_VALUE_1
#define X_PROPERTY_NAME_2
345 // x coordinate of the property name in the second and third colum
#define X_PROPERTY_VALUE_2
550 // x coordinate of the property value in the second and third colu
#define X_BUTTON_1
#define X_BUTTON_2
#define Y_PROPERTY_1
30
#define Y_PROPERTY_2
#define Y_DISTANCE
16
ExtLabelsName[];
CChartObjectLabel
CChartObjectButton ExtButtons[];
// buttons
int
ExtNumbers[];
// property indices
string
ExtNames[];
// property names
uchar
ExtDataTypes[];
uint
ExtGroupTypes[];
uchar
ExtDrawTypes[];
double
ExtMaxValue[];
double
ExtMinValue[];
300
ExtStep[];
int
ExtCount;
color
ExtColors[2];
string
ExtComments[2];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- display a comment on the chart
Comment("SomeComment");
//--- store colors in the array to be able to switch between them later
ExtColors[0]=InpFirstColor;
ExtColors[1]=InpSecondColor;
//--- store comments in the array to be able to switch between them later
ExtComments[0]="FirstComment";
ExtComments[1]="SecondComment";
//--- prepare and display the control panel for managing chart properties
if(!PrepareControls())
return(INIT_FAILED);
//--- successful execution
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- remove the comment on the chart
Comment("");
}
//+------------------------------------------------------------------+
//| Handler of a chart event
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- check the event of clicking the chart object
if(id==CHARTEVENT_OBJECT_CLICK)
{
//--- divide the object name by separator
string obj_name[];
StringSplit(sparam,'_',obj_name);
//--- check if the object is a button
if(obj_name[0]=="Button")
{
//--- receive button index
301
//+------------------------------------------------------------------+
void ChangeIntegerProperty(const int index)
{
//--- receive the current property value
long value=ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index]);
//--- define the following property value
switch(ExtDrawTypes[index])
{
case 'C':
value=GetNextColor((color)value);
break;
default:
value=(long)GetNextValue((double)value,index);
break;
}
//--- set the new property value
ChartSetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index],0,value);
}
//+------------------------------------------------------------------+
//| Changes a double property of chart
//+------------------------------------------------------------------+
void ChangeDoubleProperty(const int index)
{
//--- receive the current property value
double value=ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index]);
//--- define the following property value
value=GetNextValue(value,index);
//--- set the new property value
ChartSetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index],value);
}
//+------------------------------------------------------------------+
302
//+------------------------------------------------------------------+
void ChangeStringProperty(const int index)
{
//--- static variable for switching inside ExtComments array
static uint comment_index=1;
//--- change index for receiving another comment
comment_index=1-comment_index;
//--- set the new property value
ChartSetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[index],ExtComments[comment_index]);
}
//+------------------------------------------------------------------+
//| Gets the next property value
//+------------------------------------------------------------------+
double GetNextValue(const double value,const int index)
{
if(value+ExtStep[index]<=ExtMaxValue[index])
return(value+ExtStep[index]);
else
return(ExtMinValue[index]);
}
//+------------------------------------------------------------------+
//| Gets the next color for color type property
//+------------------------------------------------------------------+
color GetNextColor(const color clr)
{
//--- return the following color value
switch(clr)
{
case clrWhite: return(clrRed);
case clrRed:
return(clrGreen);
return(clrBlack);
default:
return(clrWhite);
}
}
//+------------------------------------------------------------------+
//| Re-draws property values
//+------------------------------------------------------------------+
void RedrawProperties(void)
{
//--- property value text
string text;
long
value;
303
//+------------------------------------------------------------------+
bool PrepareControls(void)
{
//--- allocate memory for arrays with a reserve
304
// loop variable
if(CheckNumber(ExtNumbers[ExtCount],ExtNames[ExtCount],ExtDataTypes[ExtCount],ExtGroupTypes[E
{
//--- create control elements for the property
switch(ExtGroupTypes[ExtCount])
{
case 1:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,0,X_PROPERTY_NAME_1,X_PROPERTY_VALUE_1,X_BUTTON_1,Y_PROPER
return(false);
//--- number of the elements in the first column has increased
col_1++;
break;
case 2:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,1,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,X_BUTTON_2,Y_PROPER
return(false);
//--- number of the elements in the second column has increased
col_2++;
break;
case 3:
//--- create only labels for the property
if(!ShowProperty(ExtCount,2,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,0,Y_PROPERTY_2+col_
return(false);
//--- number of the elements in the third column has increased
col_3++;
break;
}
//--- define maximum and minimum property value and step
GetMaxMinStep(ExtNumbers[ExtCount],ExtMaxValue[ExtCount],ExtMinValue[ExtCount],ExtStep[Ext
//--- increase the number of properties
ExtCount++;
}
}
305
//+------------------------------------------------------------------+
void MemoryAllocation(const int size)
{
ArrayResize(ExtLabelsName,size);
ArrayResize(ExtLabelsValue,size);
ArrayResize(ExtButtons,size);
ArrayResize(ExtNumbers,size);
ArrayResize(ExtNames,size);
ArrayResize(ExtDataTypes,size);
ArrayResize(ExtGroupTypes,size);
ArrayResize(ExtDrawTypes,size);
ArrayResize(ExtMaxValue,size);
ArrayResize(ExtMinValue,size);
ArrayResize(ExtStep,size);
}
//+------------------------------------------------------------------+
//| Checks if the property index belongs to the one of
//+------------------------------------------------------------------+
bool CheckNumber(const int ind,string &name,uchar &data_type,uint &group_type,uchar &draw_type)
{
//--- check if the property is of integer type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_INTEGER)ind);
if(_LastError==0)
{
data_type='I';
306
//+------------------------------------------------------------------+
void GetTypes(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
//--- third group properties are displayed in the second column starting from CHART_BRING_TO_TOP
if(CheckThirdGroup(property_number,group_type,draw_type))
return;
//--- check if the property belongs to the second group
//--- second group properties are displayed at the beginning of the second column
if(CheckSecondGroup(property_number,group_type,draw_type))
return;
//--- if you find yourself here, the property belongs to the first group (first column)
CheckFirstGroup(property_number,group_type,draw_type);
}
//+----------------------------------------------------------------------+
//| Checks if property belongs to the third group and
//+----------------------------------------------------------------------+
bool CheckThirdGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
switch(property_number)
{
//--- boolean properties
case CHART_IS_OBJECT:
case CHART_WINDOW_IS_VISIBLE:
draw_type='B';
break;
//--- integer properties
case CHART_VISIBLE_BARS:
case CHART_WINDOWS_TOTAL:
case CHART_WINDOW_HANDLE:
case CHART_WINDOW_YDISTANCE:
case CHART_FIRST_VISIBLE_BAR:
307
//--- in fact, this property is a command of displaying the chart on top of all the others
//--- there is no need to apply this panel, as the window will always be
//--- on top of other ones before we use it
case CHART_BRING_TO_TOP:
draw_type=' ';
break;
//--- property does not belong to the third group
default:
return(false);
}
//--- property belongs to the third group
group_type=3;
return(true);
}
//+----------------------------------------------------------------------+
//| Checks if property belongs to the second group and
//+----------------------------------------------------------------------+
bool CheckSecondGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the second group
switch(property_number)
{
//--- ENUM_CHART_MODE type property
case CHART_MODE:
draw_type='M';
break;
//--- ENUM_CHART_VOLUME_MODE type property
case CHART_SHOW_VOLUMES:
draw_type='V';
break;
//--- string property
case CHART_COMMENT:
draw_type='S';
break;
//--- color property
case CHART_COLOR_BACKGROUND:
case CHART_COLOR_FOREGROUND:
case CHART_COLOR_GRID:
case CHART_COLOR_VOLUME:
308
//+-----------------------------------------------------------------------+
void CheckFirstGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- the property belongs to the first group
group_type=1;
//--- define property display type
switch(property_number)
{
//--- integer properties
case CHART_SCALE:
case CHART_HEIGHT_IN_PIXELS:
draw_type='I';
return;
//--- double properties
case CHART_SHIFT_SIZE:
case CHART_FIXED_POSITION:
case CHART_FIXED_MAX:
case CHART_FIXED_MIN:
case CHART_POINTS_PER_BAR:
draw_type='D';
return;
//--- only boolean properties have remained
default:
draw_type='B';
return;
}
}
309
//+------------------------------------------------------------------+
bool ShowProperty(const int ind,const int type,const int x1,const int x2,
const int xb,const int y,const bool btn)
{
//--- static array for switching inside ExtColors color array
static uint color_index[3]={1,1,1};
//--- change index for receiving another color
color_index[type]=1-color_index[type];
//--- display labels and a button (if btn=true) for the property
if(!LabelCreate(ExtLabelsName[ind],"name_"+(string)ind,ExtNames[ind],ExtColors[color_index[type]
return(false);
if(!LabelCreate(ExtLabelsValue[ind],"value_"+(string)ind,"",ExtColors[color_index[type]],x2,y))
return(false);
if(btn && !ButtonCreate(ExtButtons[ind],(string)ind,xb,y+1))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Creates label
//+------------------------------------------------------------------+
bool LabelCreate(CChartObjectLabel &lbl,const string name,const string text,
const color clr,const int x,const int y)
{
if(!lbl.Create(0,"Label_"+name,0,x,y)) return(false);
if(!lbl.Description(text))
return(false);
if(!lbl.FontSize(10))
return(false);
if(!lbl.Color(clr))
return(false);
//+------------------------------------------------------------------+
bool ButtonCreate(CChartObjectButton &btn,const string name,
const int x,const int y)
{
if(!btn.Create(0,"Button_"+name,0,x,y,50,15)) return(false);
if(!btn.Description("Next"))
return(false);
if(!btn.FontSize(10))
return(false);
if(!btn.Color(clrBlack))
return(false);
if(!btn.BackColor(clrWhite))
return(false);
if(!btn.BorderColor(clrBlack))
return(false);
310
//+------------------------------------------------------------------+
void GetMaxMinStep(const int property_number,double &max,double &min,double &step)
{
double value;
//--- set values depending on the property type
switch(property_number)
{
case CHART_SCALE:
max=5;
min=0;
step=1;
break;
case CHART_MODE:
case CHART_SHOW_VOLUMES:
max=2;
min=0;
step=1;
break;
case CHART_SHIFT_SIZE:
max=50;
min=10;
step=2.5;
break;
case CHART_FIXED_POSITION:
max=90;
min=0;
step=15;
break;
case CHART_POINTS_PER_BAR:
max=19;
min=1;
step=3;
break;
case CHART_FIXED_MAX:
value=ChartGetDouble(0,CHART_FIXED_MAX);
max=value*1.25;
min=value;
step=value/32;
break;
case CHART_FIXED_MIN:
value=ChartGetDouble(0,CHART_FIXED_MIN);
max=value;
min=value*0.75;
step=value/32;
break;
case CHART_HEIGHT_IN_PIXELS:
max=700;
min=520;
311
312
Object Constants
There are 44 graphical objects that can be created and displayed in the price chart. All constants for
working with objects are divided into 9 groups:
Object types Identifiers of graphical objects;
Object properties setting and getting properties of graphical objects;
Methods of object binding constants of object positioning in the chart;
Binding corner setting the corner relative to which an object is positioned on chart;
Visibility of objects setting timeframes in which an object is visible;
Levels of Elliott Waves gradation of waves;
Gann objects trend constants for Gann fan and Gann grid;
Web colors constants of predefined web colors;
Wingdings codes of characters of the Wingdings font.
313
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_VLINE
Vertical Line
OBJ_HLINE
Horizontal Line
OBJ_TREND
Trend Line
OBJ_TRENDBYANGLE
OBJ_CYCLES
Cycle Lines
OBJ_ARROWED_LINE
Arrowed Line
OBJ_CHANNEL
Equidistant Channel
OBJ_STDDEVCHANNEL
OBJ_REGRESSION
OBJ_PITCHFORK
Andrews Pitchfork
OBJ_GANNLINE
Gann Line
OBJ_GANNFAN
Gann Fan
OBJ_GANNGRID
Gann Grid
OBJ_FIBO
Fibonacci Retracement
OBJ_FIBOTIMES
OBJ_FIBOFAN
Fibonacci Fan
OBJ_FIBOARC
Fibonacci Arcs
OBJ_FIBOCHANNEL
Fibonacci Channel
OBJ_EXPANSION
Fibonacci Expansion
OBJ_ELLIOTWAVE5
OBJ_ELLIOTWAVE3
OBJ_RECTANGLE
Rectangle
OBJ_TRIANGLE
Triangle
OBJ_ELLIPSE
Ellipse
OBJ_ARROW_THUMB_UP
Thumbs Up
OBJ_ARROW_THUMB_DOWN
Thumbs Down
OBJ_ARROW_UP
Arrow Up
314
Arrow Down
OBJ_ARROW_STOP
Stop Sign
OBJ_ARROW_CHECK
Check Sign
OBJ_ARROW_LEFT_PRICE
OBJ_ARROW_RIGHT_PRICE
OBJ_ARROW_BUY
Buy Sign
OBJ_ARROW_SELL
Sell Sign
OBJ_ARROW
Arrow
OBJ_TEXT
Text
OBJ_LABEL
Label
OBJ_BUTTON
Button
OBJ_CHART
Chart
OBJ_BITMAP
Bitmap
OBJ_BITMAP_LABEL
Bitmap Label
OBJ_EDIT
Edit
OBJ_EVENT
The
"Event"
object
corresponding to an event in
the economic calendar
OBJ_RECTANGLE_LABEL
315
OBJ_VLINE
Vertical Line.
Note
When drawing a vertical line, it is possible to set the line display mode for all chart windows
(property OBJPROP_RAY).
Example
The following script creates and moves the vertical line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Vertical Line\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="VLine";
// Line name
input int
InpDate=25;
// Event date, %
input color
InpColor=clrRed;
// Line color
InpWidth=3;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpRay=true;
316
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the vertical line
//+------------------------------------------------------------------+
bool VLineCreate(const long
chart_ID=0,
// chart's ID
const string
name="VLine",
// line name
const int
sub_window=0,
// subwindow index
datetime
time=0,
// line time
const color
clr=clrRed,
// line color
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray=true,
const bool
hidden=true,
const long
z_order=0)
{
//--- if the line time is not set, draw it via the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create a vertical line
if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create a vertical line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of displaying the line in the chart subwindows
ObjectSetInteger(chart_ID,name,OBJPROP_RAY,ray);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
317
//+------------------------------------------------------------------+
bool VLineMove(const long
chart_ID=0,
// chart's ID
time=0)
// line time
{
//--- if line time is not set, move the line to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the vertical line
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the vertical line
//+------------------------------------------------------------------+
bool VLineDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void OnStart()
{
318
319
320
OBJ_HLINE
Horizontal Line.
Example
The following script creates and moves the horizontal line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Horizontal Line\" graphical object."
#property description "Anchor point price is set in percentage of the height of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="HLine";
// Line name
input int
InpPrice=25;
// Line price, %
input color
InpColor=clrRed;
// Line color
InpWidth=3;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the horizontal line
//+------------------------------------------------------------------+
321
chart_ID=0,
// chart's ID
const string
name="HLine",
// line name
const int
sub_window=0,
// subwindow index
double
price=0,
// line price
const color
clr=clrRed,
// line color
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- if the price is not set, set it at the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- create a horizontal line
if(!ObjectCreate(chart_ID,name,OBJ_HLINE,sub_window,0,price))
{
Print(__FUNCTION__,
": failed to create a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move horizontal line
//+------------------------------------------------------------------+
bool HLineMove(const long
chart_ID=0,
// chart's ID
322
price=0)
// line price
{
//--- if the line price is not set, move it to the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move a horizontal line
if(!ObjectMove(chart_ID,name,0,0,price))
{
Print(__FUNCTION__,
": failed to move the horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a horizontal line
//+------------------------------------------------------------------+
bool HLineDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- price array size
int accuracy=1000;
323
324
325
OBJ_TREND
Trend Line.
Note
For Trend Line, it is possible to specify the mode of continuation of its display to the right and/or
left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Example
The following script creates and moves the trend line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Trend Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Trend";
// Line name
input int
InpDate1=35;
// 1 st point's date, %
input int
InpPrice1=60;
// 1 st point's price, %
input int
InpDate2=65;
// 2 nd point's date, %
input int
InpPrice2=40;
// 2 nd point's price, %
input color
InpColor=clrRed;
// Line color
326
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create a trend line by the given coordinates
//+------------------------------------------------------------------+
bool TrendCreate(const long
chart_ID=0,
// chart's ID
const string
name="TrendLine",
// line name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
// line color
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeTrendEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TREND,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
327
//+------------------------------------------------------------------+
bool TrendPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function deletes the trend line from the chart.
//+------------------------------------------------------------------+
bool TrendDelete(const long
chart_ID=0,
// chart's ID
328
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
329
price[];
330
331
332
OBJ_TRENDBYANGLE
Trend Line By Angle.
Note
For Trend Line By Angle, it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Both angle and the second anchor point's coordinates can be used to set the slope of the line.
Example
The following script creates and moves the trend line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Trend Line By Angle\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Trend";
// Line name
input int
InpDate1=50;
// 1 st point's date, %
input int
InpPrice1=75;
// 1 st point's price, %
input int
InpAngle=0;
input color
InpColor=clrRed;
// Line color
333
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=true;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create a trend line by angle
//+------------------------------------------------------------------+
bool TrendByAngleCreate(const long
chart_ID=0,
// chart's ID
const string
name="TrendLine",
// line name
const int
sub_window=0,
// subwindow index
datetime
time=0,
// point time
double
price=0,
// point price
const double
angle=45.0,
// slope angle
const color
clr=clrRed,
// line color
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=true,
const bool
hidden=true,
const long
z_order=0)
{
//--- create the second point to facilitate dragging the trend line by mouse
datetime time2=0;
double
price2=0;
334
//+------------------------------------------------------------------+
bool TrendPointChange(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change trend line's slope angle
//+------------------------------------------------------------------+
bool TrendAngleChange(const long
chart_ID=0,
// chart's ID
335
{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change the line's slope angle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the trend line
//+------------------------------------------------------------------+
bool TrendDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- set coordinates of the second, auxiliary point
//--- the second point will be 9 bars left and have the same price
datetime second_point_time[10];
CopyTime(Symbol(),Period(),time1,10,second_point_time);
336
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double
price[];
337
338
OBJ_CYCLES
Cycle Lines.
Note
The distance between the lines is set by time coordinates of two anchor points of the object.
Example
The following script creates and moves cycle lines on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates cycle lines on the chart."
#property description "Anchor point coordinates are set in percentage"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Cycles";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=45;
// 1 st point's price, %
input int
InpDate2=20;
// 2 nd point's date, %
input int
InpPrice2=55;
// 2 nd point's price, %
input color
InpColor=clrRed;
InpWidth=1;
339
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create cycle lines
//+------------------------------------------------------------------+
bool CyclesCreate(const long
chart_ID=0,
// chart's ID
const string
name="Cycles",
// object name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeCyclesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create cycle lines by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CYCLES,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create cycle lines! Error code = ",GetLastError());
return(false);
}
//--- set color of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the lines by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
340
//+------------------------------------------------------------------+
bool CyclesPointChange(const long
chart_ID=0,
// chart's ID
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the cycle lines
//+------------------------------------------------------------------+
bool CyclesDelete(const long
chart_ID=0,
// chart's ID
341
//+------------------------------------------------------------------+
void ChangeCyclesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of cycle lines' anchor points
datetime date[];
double
price[];
342
343
344
OBJ_ARROWED_LINE
Arrowed line.
Example
The following script creates and moves an arrow line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Arrowed line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpDate1=35;
// 1 st point's date, %
input int
InpPrice1=60;
// 1 st point's price, %
input int
InpDate2=65;
// 2 nd point's date, %
input int
InpPrice2=40;
// 2 nd point's price, %
input color
InpColor=clrRed;
// Line color
// Line style
input int
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
345
//+------------------------------------------------------------------+
bool ArrowedLineCreate(const long
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
// line color
// line style
const int
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeArrowedLineEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create an arrowed line by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ARROWED_LINE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create an arrowed line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
346
//+------------------------------------------------------------------+
bool ArrowedLinePointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes the arrowed line from the chart
//+------------------------------------------------------------------+
bool ArrowedLineDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
347
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double
price[];
348
349
350
OBJ_CHANNEL
Equidistant Channel
Note
For an equidistant channel, it is possible to specify the mode of its continuation to the right and/or
to the left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The mode of
filling the channel with color can also be set.
Example
The following script creates and moves an equidistant channel on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script draws \"Equidistant Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Channel";
// Channel name
input int
InpDate1=25;
// 1 st point's date, %
input int
InpPrice1=60;
// 1 st point's price, %
input int
InpDate2=65;
// 2 nd point's date, %
input int
InpPrice2=80;
// 2 nd point's price, %
input int
InpDate3=30;
// 3 rd point's date, %
351
InpPrice3=40;
// 3 rd point's price, %
input color
InpColor=clrRed;
// Channel color
InpWidth=2;
input bool
InpBack=false;
// Background channel
input bool
InpFill=false;
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create an equidistant channel by the given coordinates
//+------------------------------------------------------------------+
bool ChannelCreate(const long
chart_ID=0,
// chart's ID
const string
name="Channel",
// channel name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
// channel color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CHANNEL,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create an equidistant channel! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
352
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point
//+------------------------------------------------------------------+
bool ChannelPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
353
//+------------------------------------------------------------------+
bool ChannelDelete(const long
chart_ID=0,
// chart's ID
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the second one
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;
354
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double
price[];
if(!ChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],InpColor,
355
356
357
OBJ_STDDEVCHANNEL
Standard Deviation Channel.
Note
For Standard Deviation Channel, it is possible to specify the mode of continuation of its display to
the right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The
mode of filling the channel with color can also be set.
OBJPROP_DEVIATION property is used to change the value of the channel deviation.
Example
The following script creates and moves Standard Deviation Channel on the chart. Special functions
have been developed to create and change graphical object's properties. You can use these functions
"as is" in your own applications.
//--- description
#property description "Script draws \"Standard Deviation Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="StdDevChannel";
// Channel name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpDate2=40;
// 2 nd point's date, %
input double
InpDeviation=1.0;
// Deviation
input color
InpColor=clrRed;
// Channel color
358
InpWidth=2;
input bool
InpFill=false;
input bool
InpBack=false;
// Background channel
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create standard deviation channel by the given coordinates
//+------------------------------------------------------------------+
bool StdDevChannelCreate(const long
chart_ID=0,
// chart's ID
const string
name="Channel",
// channel name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
datetime
time2=0,
const double
deviation=1.0,
// deviation
const color
clr=clrRed,
// channel color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_STDDEVCHANNEL,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create standard deviation channel! Error code = ",GetLastError());
return(false);
}
//--- set deviation value affecting the channel width
ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation);
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the channel
359
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point
//+------------------------------------------------------------------+
bool StdDevChannelPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0)
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the channel's deviation
//+------------------------------------------------------------------+
bool StdDevChannelDeviationChange(const long
chart_ID=0,
// chart's ID
// deviation
360
//+------------------------------------------------------------------+
bool StdDevChannelDelete(const long
chart_ID=0,
// chart's ID
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
361
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double
price[];
362
363
364
OBJ_REGRESSION
Linear Regression Channel.
Note
For Linear Regression Channel, it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The mode
of filling the channel with color can also be set.
Example
The following script creates and moves Linear Regression Channel on the chart. Special functions
have been developed to create and change graphical object's properties. You can use these functions
"as is" in your own applications.
//--- description
#property description "Script draws \"Linear Regression Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpDate1=10;
// 1 st point's date, %
input int
InpDate2=40;
// 2 nd point's date, %
input color
InpColor=clrRed;
// Channel color
input int
InpWidth=2;
365
InpFill=false;
input bool
InpBack=false;
// Background channel
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Linear Regression Channel by the given coordinates
//+------------------------------------------------------------------+
bool RegressionCreate(const long
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time1=0,
datetime
time2=0,
const color
clr=clrRed,
// channel color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeRegressionEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_REGRESSION,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create linear regression channel! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the channel
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
366
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point
//+------------------------------------------------------------------+
bool RegressionPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0)
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel
//+------------------------------------------------------------------+
bool RegressionDelete(const long
chart_ID=0,
// chart's ID
367
//+-------------------------------------------------------------------------+
void ChangeRegressionEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double
price[];
368
369
370
OBJ_PITCHFORK
Andrews Pitchfork.
Note
For Andrews Pitchfork, it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Andrews Pitchfork on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Andrews Pitchfork\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Pitchfork";
// Pitchfork name
input int
InpDate1=14;
// 1 st point's date, %
input int
InpPrice1=40;
// 1 st point's price, %
input int
InpDate2=18;
// 2 nd point's date, %
input int
InpPrice2=50;
// 2 nd point's price, %
input int
InpDate3=18;
// 3 rd point's date, %
input int
InpPrice3=30;
// 3 rd point's price, %
371
InpColor=clrRed;
// Pitchfork color
InpWidth=1;
input bool
InpBack=false;
// Background pitchfork
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Andrews' Pitchfork by the given coordinates
//+------------------------------------------------------------------+
bool PitchforkCreate(const long
chart_ID=0,
// chart's ID
const string
name="Pitchfork",
// pitchfork name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create Andrews' Pitchfork by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_PITCHFORK,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create \"Andrews' Pitchfork\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
372
//--- enable (true) or disable (false) the mode of continuation of the pitchfork's display to the l
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the pitchfork's display to the r
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of Andrews' Pitchfork levels and their parameters
//+------------------------------------------------------------------+
bool PitchforkLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
373
//+------------------------------------------------------------------+
bool PitchforkPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Andrews Pitchfork
//+------------------------------------------------------------------+
bool PitchforkDelete(const long
chart_ID=0,
// chart's ID
374
//+----------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (upper right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's one
if(!time3)
time3=time2;
//--- if the third point's price is not set, move it 200 points lower than the first one
if(!price3)
price3=price1-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
375
price[];
376
377
378
OBJ_GANNLINE
Gann Line.
Note
For Gann Line, it is possible to specify the mode of continuation of its display to the right and/or
left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Both Gann angle with a scale and coordinates of the second anchor point can be used to set the slope
of the line.
Example
The following script creates and moves Gann Line on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Gann Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="GannLine";
// Line name
input int
InpDate1=20;
// 1 st point's date, %
input int
InpPrice1=75;
// 1 st point's price, %
input int
InpDate2=80;
// 2 nd point's date, %
input double
InpAngle=0.0;
// Gann Angle
379
InpScale=1.0;
// Scale
input color
InpColor=clrRed;
// Line color
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background line
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=true;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Gann Line by the coordinates, angle and scale
//+------------------------------------------------------------------+
bool GannLineCreate(const long
chart_ID=0,
// chart's ID
const string
name="GannLine",
// line name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
const double
angle=1.0,
// Gann angle
const double
scale=1.0,
// scale
const color
clr=clrRed,
// line color
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=true,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeGannLineEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Line by the given coordinates
//--- correct coordinate of the second anchor point is redefined
//--- automatically after Gann angle and/or the scale changes,
if(!ObjectCreate(chart_ID,name,OBJ_GANNLINE,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- change Gann angle
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set line color
380
//+------------------------------------------------------------------+
bool GannLinePointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
381
//+------------------------------------------------------------------+
bool GannLineAngleChange(const long
chart_ID=0,
// chart's ID
// Gann angle
{
//--- reset the error value
ResetLastError();
//--- change Gann angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change Gann angle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Line's scale
//+------------------------------------------------------------------+
bool GannLineScaleChange(const long
chart_ID=0,
// chart's ID
// scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Line from the chart
//+------------------------------------------------------------------+
bool GannLineDelete(const long
chart_ID=0,
// chart's ID
382
//+------------------------------------------------------------------+
void ChangeGannLineEmptyPoints(datetime &time1,double &price1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
383
price[];
384
385
OBJ_GANNFAN
Gann Fan.
Note
For Gann Fan, it is possible to specify trend type from ENUM_GANN_DIRECTION enumeration. By
adjusting the scale value (OBJPROP_SCALE), it is possible to change slope angle of the fan lines.
Example
The following script creates and moves Gann Fan on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Gann Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="GannFan";
// Fan name
input int
InpDate1=15;
// 1 st point's date, %
input int
InpPrice1=25;
// 1 st point's price, %
input int
InpDate2=85;
// 2 nd point's date, %
input double
InpScale=2.0;
// Scale
input bool
InpDirection=false;
// Trend direction
input color
InpColor=clrRed;
// Fan color
386
InpWidth=1;
input bool
InpBack=false;
// Background fan
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Gann Fan
//+------------------------------------------------------------------+
bool GannFanCreate(const long
chart_ID=0,
// chart's ID
const string
name="GannFan",
// fan name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
const double
scale=1.0,
// scale
const bool
direction=true,
// trend direction
const color
clr=clrRed,
// fan color
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeGannFanEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNFAN,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set fan color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving
387
//+------------------------------------------------------------------+
bool GannFanPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the fan's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's scale
//+------------------------------------------------------------------+
bool GannFanScaleChange(const long
chart_ID=0,
// chart's ID
// scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
388
//+------------------------------------------------------------------+
bool GannFanDirectionChange(const long
chart_ID=0,
// chart's ID
{
//--- reset the error value
ResetLastError();
//--- change Gann Fan's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart
//+------------------------------------------------------------------+
bool GannFanDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
389
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of fan's anchor points
datetime date[];
double
price[];
390
391
392
OBJ_GANNGRID
Gann Grid.
Note
For Gann Grid, it is possible to specify trend type from ENUM_GANN_DIRECTION. By adjusting the
scale value (OBJPROP_SCALE), it is possible to change slope angle of the grid lines.
Example
The following script creates and moves Gann Grid on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Gann Grid\" graphical object."
#property description "Anchor point coordinates of the grid are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="GannGrid";
// Grid name
input int
InpDate1=15;
// 1 st point's date, %
input int
InpPrice1=25;
// 1 st point's price, %
input int
InpDate2=35;
// 2 nd point's date, %
input double
InpScale=3.0;
// Scale
input bool
InpDirection=false;
// Trend direction
input color
InpColor=clrRed;
// Grid color
393
InpWidth=1;
input bool
InpBack=false;
// Background grid
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Gann Grid
//+------------------------------------------------------------------+
bool GannGridCreate(const long
chart_ID=0,
// chart's ID
const string
name="GannGrid",
// grid name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
const double
scale=1.0,
// scale
const bool
direction=true,
// trend direction
const color
clr=clrRed,
// grid color
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeGannGridEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Grid by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNGRID,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set grid color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the grid for moving
394
//+------------------------------------------------------------------+
bool GannGridPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the grid's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's scale
//+------------------------------------------------------------------+
bool GannGridScaleChange(const long
chart_ID=0,
// chart's ID
// scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
395
//+------------------------------------------------------------------+
bool GannGridDirectionChange(const long
chart_ID=0,
// chart's ID
direction=true)
// trend direction
{
//--- reset the error value
ResetLastError();
//--- change Gann Grid's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart
//+------------------------------------------------------------------+
bool GannGridDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
396
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing grid anchor points' coordinates
datetime date[];
double
price[];
397
398
399
OBJ_FIBO
Fibonacci Retracement.
Note
For Fibonacci Retracement, it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Retracement on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script draws \"Fibonacci Retracement\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboLevels";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=65;
// 1 st point's price, %
input int
InpDate2=90;
// 2 nd point's date, %
input int
InpPrice2=85;
// 2 nd point's price, %
input color
InpColor=clrRed;
// Object color
400
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Retracement by the given coordinates
//+------------------------------------------------------------------+
bool FiboLevelsCreate(const long
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
// object color
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboLevelsEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Retracement by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBO,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Retracement\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
401
//--- enable (true) or disable (false) the mode of continuation of the object's display to the left
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the object's display to the righ
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters
//+------------------------------------------------------------------+
bool FiboLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
402
//+------------------------------------------------------------------+
bool FiboLevelsPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Retracement
//+------------------------------------------------------------------+
bool FiboLevelsDelete(const long
chart_ID=0,
// chart's ID
403
//+------------------------------------------------------------------+
void ChangeFiboLevelsEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Retracement anchor points
datetime date[];
double
price[];
404
405
406
OBJ_FIBOTIMES
Fibonacci Time Zones.
Note
For "Fibonacci Time Zones", it is possible to specify the number of line-levels, their values and
color.
Example
The following script creates and moves Fibonacci Time Zones on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script draws \"Fibonacci Time Zones\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboTimes";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=45;
// 1 st point's price, %
input int
InpDate2=20;
// 2 nd point's date, %
input int
InpPrice2=55;
// 2 nd point's price, %
input color
InpColor=clrRed;
// Object color
InpWidth=2;
// Line width
407
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Time Zones by the given coordinates
//+------------------------------------------------------------------+
bool FiboTimesCreate(const long
chart_ID=0,
// chart's ID
const string
name="FiboTimes",
// object name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
// object color
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboTimesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Time Zones by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOTIMES,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Time Zones\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
408
//+------------------------------------------------------------------+
bool FiboTimesLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Time Zones anchor point
//+------------------------------------------------------------------+
bool FiboTimesPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
409
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Time Zones
//+------------------------------------------------------------------+
bool FiboTimesDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeFiboTimesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
410
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Time Zones anchor points
datetime date[];
double
price[];
411
412
413
OBJ_FIBOFAN
Fibonacci Fan.
Note
For "Fibonacci Fan", it is possible to specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Fan on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Fibonacci Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboFan";
// Fan name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=25;
// 1 st point's price, %
input int
InpDate2=30;
// 2 nd point's date, %
input int
InpPrice2=50;
// 2 nd point's price, %
input color
InpColor=clrRed;
InpWidth=2;
// Line width
414
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Fan by the given coordinates
//+------------------------------------------------------------------+
bool FiboFanCreate(const long
chart_ID=0,
// chart's ID
const string
name="FiboFan",
// fan name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboFanEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOFAN,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
415
//+------------------------------------------------------------------+
bool FiboFanLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Fan anchor point
//+------------------------------------------------------------------+
bool FiboFanPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
416
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Fan
//+------------------------------------------------------------------+
bool FiboFanDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeFiboFanEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
417
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Fan anchor points
datetime date[];
double
price[];
418
419
420
OBJ_FIBOARC
Fibonacci Arcs.
Note
For "Fibonacci Arcs", it is possible to specify the display mode of the entire ellipse. Curvature radius
can be specified by changing the scale and coordinates of the anchor points.
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Arcs on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Fibonacci Arcs\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboArc";
// Object name
input int
InpDate1=25;
// 1 st point's date, %
input int
InpPrice1=25;
// 1 st point's price, %
input int
InpDate2=35;
// 2 nd point's date, %
input int
InpPrice2=55;
// 2 nd point's price, %
input double
InpScale=3.0;
// Scale
421
InpFullEllipse=true;
input color
InpColor=clrRed;
// Line color
InpWidth=2;
// Line width
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Arcs by the given coordinates
//+------------------------------------------------------------------+
bool FiboArcCreate(const long
chart_ID=0,
// chart's ID
const string
name="FiboArc",
// object name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const double
scale=1.0,
// scale
const bool
const color
clr=clrRed,
// line color
// line style
const int
width=1,
// line width
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboArcEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Arcs by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOARC,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- set the scale
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set display of the arcs as a full ellipse (true) or a half of it (false)
ObjectSetInteger(chart_ID,name,OBJPROP_ELLIPSE,full_ellipse);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
422
//+------------------------------------------------------------------+
bool FiboArcLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
423
//+------------------------------------------------------------------+
bool FiboArcPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Arcs
//+------------------------------------------------------------------+
bool FiboArcDelete(const long
chart_ID=0,
// chart's ID
424
//+------------------------------------------------------------------+
void ChangeFiboArcEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points below the second one
if(!price1)
price1=price2-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Arcs anchor points
datetime date[];
double
price[];
425
426
427
OBJ_FIBOCHANNEL
Fibonacci Channel.
Note
For Fibonacci Channel, it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Channel on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Fibonacci Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboChannel";
// Channel name
input int
InpDate1=20;
// 1 st point's date, %
input int
InpPrice1=10;
// 1 st point's price, %
input int
InpDate2=60;
// 2 nd point's date, %
input int
InpPrice2=30;
// 2 nd point's price, %
input int
InpDate3=20;
// 3 rd point's date, %
428
InpPrice3=25;
// 3 rd point's price, %
input color
InpColor=clrRed;
// Channel color
InpWidth=2;
input bool
InpBack=false;
// Background channel
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Channel by the given coordinates
//+------------------------------------------------------------------+
bool FiboChannelCreate(const long
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
// channel color
const int
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
const bool
ray_right=false,
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOCHANNEL,sub_window,time1,price1,time2,price2,time3,price3
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Channel\"! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
429
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters
//+------------------------------------------------------------------+
bool FiboChannelLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
430
//+------------------------------------------------------------------+
bool FiboChannelPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel
//+------------------------------------------------------------------+
bool FiboChannelDelete(const long
chart_ID=0,
// chart's ID
431
//+------------------------------------------------------------------+
void ChangeFiboChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the second one
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
432
price[];
433
434
435
OBJ_EXPANSION
Fibonacci Expansion.
Note
For "Fibonacci Expansion", it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Expansion on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script draws \"Fibonacci Expansion\"graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="FiboExpansion";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=55;
// 1 st point's price, %
input int
InpDate2=30;
// 2 nd point's date, %
input int
InpPrice2=10;
// 2 nd point's price, %
input int
InpDate3=80;
// 3 rd point's date, %
436
InpPrice3=75;
// 3 rd point's price, %
input color
InpColor=clrRed;
// Object color
InpWidth=2;
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpRayLeft=false;
input bool
InpRayRight=false;
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Fibonacci Extension by the given coordinates
//+------------------------------------------------------------------+
bool FiboExpansionCreate(const long
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
// object color
const int
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
ray_left=false,
// object's continuation to th
const bool
ray_right=false,
// object's continuation to th
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeFiboExpansionEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Extension by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_EXPANSION,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Extension\"! Error code = ",GetLastError());
return(false);
}
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
437
//--- enable (true) or disable (false) the mode of continuation of the object's visualization to th
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the object's visualization to th
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters
//+------------------------------------------------------------------+
bool FiboExpansionLevelsSet(int
levels,
double
&values[],
color
&colors[],
ENUM_LINE_STYLE &styles[],
int
&widths[],
const long
chart_ID=0,
// chart's ID
const string
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
438
//+------------------------------------------------------------------+
bool FiboExpansionPointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Expansion
//+------------------------------------------------------------------+
bool FiboExpansionDelete(const long
chart_ID=0,
// chart's ID
439
//+------------------------------------------------------------------+
void ChangeFiboExpansionEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the third (right) point's time is not set, it will be on the current bar
if(!time3)
time3=TimeCurrent();
//--- if the third point's price is not set, it will have Bid value
if(!price3)
price3=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the third one
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
if(!time1)
{
CopyTime(Symbol(),Period(),time3,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it is equal to the third point's one
if(!price1)
price1=price3;
//--- if the second point's time is not set, it is located 7 bars left from the third one
if(!time2)
time2=temp[2];
//--- if the second point's price is not set, move it 250 points lower than the first one
if(!price2)
price2=price1-250*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
440
price[];
441
442
443
OBJ_ELLIOTWAVE5
Elliott Motive Wave.
Note
For "Elliott Motive Wave", it is possible to enable/disable the mode of connecting points by lines
(OBJPROP_DRAWLINES property), as well as set the level of wave positioning (from
ENUM_ELLIOT_WAVE_DEGREE enumeration).
Example
The following script creates and moves Elliott motive wave on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Elliott Motive Wave\"."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ElliotWave5";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=90;
// 1 st point's price, %
input int
InpDate2=20;
// 2 nd point's date, %
input int
InpPrice2=40;
// 2 nd point's price, %
input int
InpDate3=30;
// 3 rd point's date, %
444
InpPrice3=60;
// 3 rd point's price, %
input int
InpDate4=40;
// 4 th point's date, %
input int
InpPrice4=10;
// 4 th point's price, %
input int
InpDate5=60;
// 5 th point's date, %
input int
InpPrice5=40;
// 5 th point's price, %
InpDrawLines=true;
input color
InpColor=clrRed;
input ENUM_LINE_STYLE
InpStyle=STYLE_DASH;
input int
InpWidth=2;
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create "Elliott Motive Wave" by the given coordinates
//+------------------------------------------------------------------+
bool ElliotWave5Create(const long
chart_ID=0,
// chart's ID
name="ElliotWave5",
// wave name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
datetime
time4=0,
double
price4=0,
datetime
time5=0,
double
price5=0,
const string
draw_lines=true,
const color
clr=clrRed,
// object color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeElliotWave5EmptyPoints(time1,price1,time2,price2,time3,price3,time4,price4,time5,price5);
//--- reset the error value
ResetLastError();
//--- Create "Elliott Motive Wave" by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIOTWAVE5,sub_window,time1,price1,time2,price2,time3,
price3,time4,price4,time5,price5))
{
Print(__FUNCTION__,
445
//+------------------------------------------------------------------+
bool ElliotWave5PointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
446
//+------------------------------------------------------------------+
bool ElliotWave5Delete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeElliotWave5EmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3,
datetime &time4,double &price4,
datetime &time5,double &price5)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
//--- receive data
CopyTime(Symbol(),Period(),TimeCurrent(),10,temp);
//--- receive the value of one point on the current chart
double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the first point's time is not set, it will be 9 bars left from the last bar
if(!time1)
time1=temp[0];
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it will be 7 bars left from the last bar
if(!time2)
time2=temp[2];
447
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100 ||
InpDate4<0 || InpDate4>100 || InpPrice4<0 || InpPrice4>100 ||
InpDate5<0 || InpDate5>100 || InpPrice5<0 || InpPrice5>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double
price[];
448
449
450
451
OBJ_ELLIOTWAVE3
Elliott Correction Wave.
Note
For "Elliott Correction Wave", it is possible to enable/disable the mode of connecting points by lines
(OBJPROP_DRAWLINES property), as well as set the level of wave positioning (from
ENUM_ELLIOT_WAVE_DEGREE enumeration).
Example
The following script creates and moves Elliott correction wave on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script draws \"Elliott Correction Wave\" graphical object."
#property description "Anchor point coordinates are set in percentage of the chart's window"
#property description "size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ElliotWave3";
// Object name
input int
InpDate1=10;
// 1 st point's date, %
input int
InpPrice1=90;
// 1 st point's price, %
input int
InpDate2=30;
// 2 nd point's date, %
input int
InpPrice2=10;
// 2 nd point's price, %
input int
InpDate3=50;
// 3 rd point's date, %
452
InpPrice3=40;
// 3 rd point's price, %
InpDrawLines=true;
input color
InpColor=clrRed;
input ENUM_LINE_STYLE
InpStyle=STYLE_DASH;
input int
InpWidth=2;
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create "Elliott Correction Wave" by the given coordinates
//+------------------------------------------------------------------+
bool ElliotWave3Create(const long
chart_ID=0,
// chart's ID
const string
name="ElliotWave3",
// wave name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
draw_lines=true,
const color
clr=clrRed,
// object color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeElliotWave3EmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- Create "Elliott Correction Wave" by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIOTWAVE3,sub_window,time1,price1,time2,price2,time3,price3
{
Print(__FUNCTION__,
": failed to create \"Elliott Correction Wave\"! Error code = ",GetLastError());
return(false);
}
//--- set degree (wave size)
ObjectSetInteger(chart_ID,name,OBJPROP_DEGREE,degree);
//--- enable (true) or disable (false) the mode of displaying the lines
ObjectSetInteger(chart_ID,name,OBJPROP_DRAWLINES,draw_lines);
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
453
//+------------------------------------------------------------------+
bool ElliotWave3PointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Elliott Correction Wave
//+------------------------------------------------------------------+
bool ElliotWave3Delete(const long
chart_ID=0,
// chart's ID
454
//+------------------------------------------------------------------+
void ChangeElliotWave3EmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
//--- receive data
CopyTime(Symbol(),Period(),TimeCurrent(),10,temp);
//--- receive the value of one point on the current chart
double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the first point's time is not set, it will be 9 bars left from the last bar
if(!time1)
time1=temp[0];
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it will be 5 bars left from the last bar
if(!time2)
time2=temp[4];
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*point;
//--- if the third point's time is not set, it will be 1 bar left from the last bar
if(!time3)
time3=temp[8];
//--- if the third point's price is not set, move it 200 points lower than the first one
if(!price3)
price3=price1-200*point;
}
//+------------------------------------------------------------------+
455
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double
price[];
456
457
458
OBJ_RECTANGLE
Rectangle.
Note
For rectangle, the mode of filling with color can be set using OBJPROP_FILL property.
Example
The following script creates and moves the rectangle on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates rectangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpDate1=40;
// 1 st point's date, %
input int
InpPrice1=40;
// 1 st point's price, %
input int
InpDate2=60;
// 2 nd point's date, %
input int
InpPrice2=60;
// 2 nd point's price, %
input color
InpColor=clrRed;
// Rectangle color
InpWidth=2;
459
InpFill=true;
input bool
InpBack=false;
// Background rectangle
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create rectangle by the given coordinates
//+------------------------------------------------------------------+
bool RectangleCreate(const long
chart_ID=0,
// chart's ID
const string
name="Rectangle",
// rectangle name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
const color
clr=clrRed,
// rectangle color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeRectangleEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a rectangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a rectangle! Error code = ",GetLastError());
return(false);
}
//--- set rectangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the style of rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the rectangle
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the rectangle for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
460
//+------------------------------------------------------------------+
bool RectanglePointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle
//+------------------------------------------------------------------+
bool RectangleDelete(const long
chart_ID=0,
// chart's ID
461
//+------------------------------------------------------------------+
void ChangeRectangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing rectangle anchor points' coordinates
datetime date[];
462
price[];
463
464
OBJ_TRIANGLE
Triangle.
Note
For triangle, the mode of filling with color can be set using OBJPROP_FILL property.
Example
The following script creates and moves the triangle on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates triangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Triangle";
// Triangle name
input int
InpDate1=25;
// 1 st point's date, %
input int
InpPrice1=50;
// 1 st point's price, %
input int
InpDate2=70;
// 2 nd point's date, %
input int
InpPrice2=70;
// 2 nd point's price, %
input int
InpDate3=65;
// 3 rd point's date, %
input int
InpPrice3=20;
// 3 rd point's price, %
input color
InpColor=clrRed;
// Triangle color
465
InpWidth=2;
input bool
InpFill=false;
input bool
InpBack=false;
// Background triangle
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create triangle by the given coordinates
//+------------------------------------------------------------------+
bool TriangleCreate(const long
chart_ID=0,
// chart's ID
const string
name="Triangle",
// triangle name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
// triangle color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeTriangleEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create triangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TRIANGLE,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create a triangle! Error code = ",GetLastError());
return(false);
}
//--- set triangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the triangle
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
466
//+------------------------------------------------------------------+
bool TrianglePointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the triangle
//+------------------------------------------------------------------+
bool TriangleDelete(const long
chart_ID=0,
// chart's ID
467
//+------------------------------------------------------------------+
void ChangeTriangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's date
if(!time3)
time3=time2;
//--- if the third point's price is not set, it is equal to the first point's one
if(!price3)
price3=price1;
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
468
price[];
469
470
471
OBJ_ELLIPSE
Ellipse.
Note
For ellipse, the mode of filling with color can be set using OBJPROP_FILL property.
Example
The following script creates and moves the ellipse on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates ellipse on the chart."
#property description "Anchor point coordinates are set"
#property description "in percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Ellipse";
// Ellipse name
input int
InpDate1=30;
// 1 st point's date, %
input int
InpPrice1=20;
// 1 st point's price, %
input int
InpDate2=70;
// 2 nd point's date, %
input int
InpPrice2=80;
// 2 nd point's price, %
input int
InpDate3=50;
// 3 rd point's date, %
input int
InpPrice3=60;
// 3 rd point's price, %
input color
InpColor=clrRed;
// Ellipse color
472
InpWidth=2;
input bool
InpFill=false;
input bool
InpBack=false;
// Background ellipse
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create an ellipse by the given coordinates
//+------------------------------------------------------------------+
bool EllipseCreate(const long
chart_ID=0,
// chart's ID
const string
name="Ellipse",
// ellipse name
const int
sub_window=0,
// subwindow index
datetime
time1=0,
double
price1=0,
datetime
time2=0,
double
price2=0,
datetime
time3=0,
double
price3=0,
const color
clr=clrRed,
// ellipse color
width=1,
const bool
fill=false,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor points' coordinates if they are not set
ChangeEllipseEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create an ellipse by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIPSE,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create an ellipse! Error code = ",GetLastError());
return(false);
}
//--- set an ellipse color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the ellipse
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the ellipse for moving
473
//+------------------------------------------------------------------+
bool EllipsePointChange(const long
chart_ID=0,
// chart's ID
point_index=0,
datetime
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete ellipse
//+------------------------------------------------------------------+
bool EllipseDelete(const long
chart_ID=0,
// chart's ID
474
//+------------------------------------------------------------------+
void ChangeEllipseEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's date
if(!time3)
time3=time2;
//--- if the third point's price is not set, it is equal to the first point's one
if(!price3)
price3=price1;
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
475
price[];
476
477
OBJ_ARROW_THUMB_UP
Thumbs Up sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Thumbs Up sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Thumbs Up\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ThumbUp";
// Sign name
input int
InpDate=75;
input int
InpPrice=25;
InpColor=clrRed;
// Sign color
478
InpStyle=STYLE_DOT;
input int
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Thumbs Up sign
//+------------------------------------------------------------------+
bool ArrowThumbUpCreate(const long
chart_ID=0,
// chart's ID
const string
name="ThumbUp",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
479
//+------------------------------------------------------------------+
bool ArrowThumbUpMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Up sign anchor type
//+------------------------------------------------------------------+
bool ArrowThumbUpAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="ThumbUp",
// object name
480
//+------------------------------------------------------------------+
bool ArrowThumbUpDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
481
price[];
482
483
OBJ_ARROW_THUMB_DOWN
Thumbs Down sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Thumbs Down sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Thumbs Down\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ThumbDown";
// Sign name
input int
InpDate=25;
input int
InpPrice=75;
484
InpColor=clrRed;
// Sign color
input ENUM_LINE_STYLE
InpStyle=STYLE_DOT;
input int
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Thumbs Down sign
//+------------------------------------------------------------------+
bool ArrowThumbDownCreate(const long
chart_ID=0,
// chart's ID
name="ThumbDown",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const string
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
485
//+------------------------------------------------------------------+
bool ArrowThumbDownMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Down sign anchor type
//+------------------------------------------------------------------+
bool ArrowThumbDownAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="ThumbDown",
// object name
486
//+------------------------------------------------------------------+
bool ArrowThumbDownDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
487
price[];
488
489
OBJ_ARROW_UP
Arrow Up sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Arrow Up sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Arrow Up\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ArrowUp";
// Sign name
input int
InpDate=25;
input int
InpPrice=25;
InpColor=clrRed;
// Sign color
490
InpStyle=STYLE_DOT;
input int
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Arrow Up sign
//+------------------------------------------------------------------+
bool ArrowUpCreate(const long
chart_ID=0,
// chart's ID
const string
name="ArrowUp",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
491
//+------------------------------------------------------------------+
bool ArrowUpMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type
//+------------------------------------------------------------------+
bool ArrowUpAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="ArrowUp",
// object name
492
//+------------------------------------------------------------------+
bool ArrowUpDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
493
price[];
494
495
OBJ_ARROW_DOWN
Arrow Down sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Arrow Down sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Arrow Down\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ArrowDown";
// Sign name
input int
InpDate=75;
input int
InpPrice=75;
InpColor=clrRed;
// Sign color
input ENUM_LINE_STYLE
InpStyle=STYLE_DOT;
496
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Arrow Down sign
//+------------------------------------------------------------------+
bool ArrowDownCreate(const long
chart_ID=0,
// chart's ID
name="ArrowDown",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const string
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
497
//+------------------------------------------------------------------+
bool ArrowDownMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type
//+------------------------------------------------------------------+
bool ArrowDownAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="ArrowDown",
// object name
498
//+------------------------------------------------------------------+
bool ArrowDownDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
499
price[];
500
501
OBJ_ARROW_STOP
Stop sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Stop sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Stop\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="ArrowStop";
// Sign name
input int
InpDate=10;
input int
InpPrice=50;
InpColor=clrRed;
// Sign color
502
InpStyle=STYLE_DOT;
input int
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Stop sign
//+------------------------------------------------------------------+
bool ArrowStopCreate(const long
chart_ID=0,
// chart's ID
const string
name="ArrowStop",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_STOP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
503
//+------------------------------------------------------------------+
bool ArrowStopMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Stop sign anchor type
//+------------------------------------------------------------------+
bool ArrowStopAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="ArrowStop",
// object name
504
//+------------------------------------------------------------------+
bool ArrowStopDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
505
price[];
506
507
OBJ_ARROW_CHECK
Check sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
Example
The following script creates and moves Check sign on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Check\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpDate=10;
input int
InpPrice=50;
InpColor=clrRed;
// Sign color
508
InpStyle=STYLE_DOT;
input int
InpWidth=5;
// Sign size
input bool
InpBack=false;
// Background sign
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Check sign
//+------------------------------------------------------------------+
bool ArrowCheckCreate(const long
chart_ID=0,
// chart's ID
const string
name="ArrowCheck",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
clr=clrRed,
// sign color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// sign size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_CHECK,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
509
//+------------------------------------------------------------------+
bool ArrowCheckMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Check anchor type
//+------------------------------------------------------------------+
bool ArrowCheckAnchorChange(const long
const string
chart_ID=0,
// chart's ID
510
//+------------------------------------------------------------------+
bool ArrowCheckDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
511
price[];
512
513
OBJ_ARROW_LEFT_PRICE
Left Price Label
Example
The following script creates and moves left price label on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates the left price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="LeftPrice";
input int
InpDate=100;
input int
InpPrice=10;
input color
InpColor=clrRed;
input ENUM_LINE_STYLE
input int
InpWidth=2;
input bool
InpBack=false;
// Background label
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the left price label
514
chart_ID=0,
// chart's ID
const string
name="LeftPrice",
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const color
clr=clrRed,
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_LEFT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the left price label! Error code = ",GetLastError());
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point
//+------------------------------------------------------------------+
515
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the left price label from the chart
//+------------------------------------------------------------------+
bool ArrowLeftPriceDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
516
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double
price[];
517
518
OBJ_ARROW_RIGHT_PRICE
Right Price Label.
Example
The following script creates and moves right price label on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates the right price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpDate=0;
input int
InpPrice=90;
input color
InpColor=clrRed;
input ENUM_LINE_STYLE
input int
InpWidth=2;
input bool
InpBack=false;
// Background label
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the right price label
519
chart_ID=0,
// chart's ID
const string
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const color
clr=clrRed,
width=1,
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_RIGHT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the right price label! Error code = ",GetLastError());
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point
//+------------------------------------------------------------------+
520
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the right price label from the chart
//+------------------------------------------------------------------+
bool ArrowRightPriceDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
521
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double
price[];
522
523
OBJ_ARROW_BUY
Buy sign.
Example
The following script creates and moves Buy sign on the chart. Special functions have been developed
to create and change graphical object's properties. You can use these functions "as is" in your own
applications.
//--- description
#property description "Script draws \"Buy\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'3,95,172'; // Color of signs
//+------------------------------------------------------------------+
//| Create Buy sign
//+------------------------------------------------------------------+
bool ArrowBuyCreate(const long
chart_ID=0,
// chart's ID
const string
name="ArrowBuy",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const color
clr=C'3,95,172',
// sign color
width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
524
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_BUY,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point
//+------------------------------------------------------------------+
bool ArrowBuyMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
525
//+------------------------------------------------------------------+
bool ArrowBuyDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double
low[];
double
526
527
528
OBJ_ARROW_SELL
Sell sign.
Example
The following script creates and moves Sell sign on the chart. Special functions have been developed
to create and change graphical object's properties. You can use these functions "as is" in your own
applications.
//--- description
#property description "Script draws \"Sell\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'225,68,29'; // Color of signs
//+------------------------------------------------------------------+
//| Create Sell sign
//+------------------------------------------------------------------+
bool ArrowSellCreate(const long
chart_ID=0,
// chart's ID
const string
name="ArrowSell",
// sign name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const color
clr=C'225,68,29',
// sign color
width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
529
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_SELL,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point
//+------------------------------------------------------------------+
bool ArrowSellMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
530
//+------------------------------------------------------------------+
bool ArrowSellDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double
low[];
double
531
532
533
OBJ_ARROW
Arrow object.
Note
Anchor point position relative to the object can be selected from ENUM_ARROW_ANCHOR.
Large arrows (more than 5) can only be created by setting the appropriate OBJPROP_WIDTH property
value when writing a code in MetaEditor.
The necessary arrow type can be selected by setting one of the Wingdings font's symbol codes.
Example
The following script creates Arrow object on the chart and changes its type. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script creates a random arrow in the chart window."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Arrow";
// Arrow name
input int
InpDate=50;
input int
InpPrice=50;
// Anchor type
534
input ENUM_LINE_STYLE
InpStyle=STYLE_SOLID;
input int
InpWidth=10;
// Arrow size
input bool
InpBack=false;
// Background arrow
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the arrow
//+------------------------------------------------------------------+
bool ArrowCreate(const long
chart_ID=0,
// chart's ID
name="Arrow",
// arrow name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const uchar
arrow_code=252,
// arrow code
const string
clr=clrRed,
// arrow color
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
width=3,
// arrow size
const bool
back=false,
// in the background
const bool
selection=true,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create an arrow
if(!ObjectCreate(chart_ID,name,OBJ_ARROW,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create an arrow! Error code = ",GetLastError());
return(false);
}
//--- set the arrow code
ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,arrow_code);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the arrow color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the arrow's size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the arrow by mouse
535
//+------------------------------------------------------------------+
bool ArrowMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the arrow code
//+------------------------------------------------------------------+
bool ArrowCodeChange(const long
chart_ID=0,
// chart's ID
code=252)
// arrow code
{
//--- reset the error value
ResetLastError();
//--- change the arrow code
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,code))
{
536
//+------------------------------------------------------------------+
bool ArrowAnchorChange(const long
const string
chart_ID=0,
// chart's ID
name="Arrow",
// object name
//+------------------------------------------------------------------+
bool ArrowDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
537
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double
price[];
538
539
OBJ_TEXT
Text object.
Note
Anchor point position relative to the text can be selected from ENUM_ANCHOR_POINT enumeration.
You can also change text slope angle using OBJPROP_ANGLE property.
Example
The following script creates several Text objects on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates \"Text\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpFont="Arial";
// Font
input int
InpFontSize=10;
// Font size
input color
InpColor=clrRed;
// Color
input double
InpAngle=90.0;
InpBack=false;
// Background object
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
540
//+------------------------------------------------------------------+
bool TextCreate(const long
chart_ID=0,
// chart's ID
name="Text",
// object name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const string
text="Text",
const string
font="Arial",
// font
const int
font_size=10,
// font size
const color
clr=clrRed,
// color
const double
angle=0.0,
// text slope
const string
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeTextEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create Text object
if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the object by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
541
//+------------------------------------------------------------------+
bool TextMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the object text
//+------------------------------------------------------------------+
bool TextChange(const long
chart_ID=0,
// chart's ID
542
//+------------------------------------------------------------------+
bool TextDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeTextEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double
low[];
double
543
if(!TextCreate(0,"TextHigh_"+(string)i,0,date[i],high[i],DoubleToString(high[i],5),InpFont,In
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
if(!TextCreate(0,"TextLow_"+(string)i,0,date[i],low[i],DoubleToString(low[i],5),InpFont,InpFo
InpColor,-InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- check if the script's operation has been forcefully disabled
544
545
OBJ_LABEL
Label object.
Note
Anchor point position relative to the label can be selected from ENUM_ANCHOR_POINT enumeration.
Anchor point coordinates are set in pixels.
You can also select text label anchoring corner from ENUM_BASE_CORNER enumeration.
Example
The following script creates and moves Edit object on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates \"Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Label";
// Label name
input int
InpX=150;
// X-axis distance
input int
InpY=150;
// Y-axis distance
input string
InpFont="Arial";
// Font
input int
InpFontSize=14;
// Font size
input color
InpColor=clrRed;
// Color
input double
InpAngle=0.0;
546
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create a text label
//+------------------------------------------------------------------+
bool LabelCreate(const long
chart_ID=0,
// chart's ID
const string
name="Label",
// label name
const int
sub_window=0,
// subwindow index
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const ENUM_BASE_CORNER
const string
text="Label",
// text
const string
font="Arial",
// font
const int
font_size=10,
// font size
const color
clr=clrRed,
// color
const double
angle=0.0,
// text slope
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create a text label
if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create text label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
547
//+------------------------------------------------------------------+
bool LabelMove(const long
chart_ID=0,
// chart's ID
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the text label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the label
//+------------------------------------------------------------------+
bool LabelChangeCorner(const long
const string
chart_ID=0,
// chart's ID
name="Label",
// label name
548
//+------------------------------------------------------------------+
bool LabelTextChange(const long
chart_ID=0,
// chart's ID
// text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a text label
//+------------------------------------------------------------------+
bool LabelDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
549
550
551
//+------------------------------------------------------------------+
bool MoveAndTextChange(const int x,const int y,string text)
{
//--- move the label
if(!LabelMove(0,InpName,x,y))
return(false);
//--- change the label text
StringConcatenate(text,text,x,",",y);
if(!LabelTextChange(0,InpName,text))
return(false);
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return(false);
//--- redraw the chart
ChartRedraw();
// 0.01 seconds of delay
552
553
OBJ_BUTTON
Button object.
Note
Anchor point coordinates are set in pixels. You can select button anchoring corner from
ENUM_BASE_CORNER.
Example
The following script creates and moves Button object on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates the button on the chart."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Button";
// Button name
InpFont="Arial";
// Font
input int
InpFontSize=14;
// Font size
input color
InpColor=clrBlack;
// Text color
input color
input color
InpBorderColor=clrNONE;
// Border color
input bool
InpState=false;
// Pressed/Released
input bool
InpBack=false;
// Background object
input bool
InpSelection=false;
// Highlight to move
554
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create the button
//+------------------------------------------------------------------+
bool ButtonCreate(const long
chart_ID=0,
// chart's ID
const string
name="Button",
// button name
const int
sub_window=0,
// subwindow index
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const int
width=50,
// button width
const int
height=18,
// button height
const ENUM_BASE_CORNER
const string
text="Button",
// text
const string
font="Arial",
// font
const int
font_size=10,
// font size
const color
clr=clrBlack,
// text color
const color
back_clr=C'236,233,216',
// background color
const color
border_clr=clrNONE,
// border color
const bool
state=false,
// pressed/released
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create the button
if(!ObjectCreate(chart_ID,name,OBJ_BUTTON,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create the button! Error code = ",GetLastError());
return(false);
}
//--- set button coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set button size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set text color
555
//+------------------------------------------------------------------+
bool ButtonMove(const long
chart_ID=0,
// chart's ID
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the button
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the button! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the button! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button size
//+------------------------------------------------------------------+
bool ButtonChangeSize(const long
chart_ID=0,
// chart's ID
556
width=50,
// button width
const int
height=18)
// button height
{
//--- reset the error value
ResetLastError();
//--- change the button size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the button width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the button height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the button
//+------------------------------------------------------------------+
bool ButtonChangeCorner(const long
const string
chart_ID=0,
// chart's ID
name="Button",
// button name
//+------------------------------------------------------------------+
bool ButtonTextChange(const long
chart_ID=0,
// chart's ID
// text
{
//--- reset the error value
557
//+------------------------------------------------------------------+
bool ButtonDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define the step for changing the button size
558
559
560
OBJ_CHART
Chart object.
Note
Anchor point coordinates are set
ENUM_BASE_CORNER enumeration.
in
pixels. You
can
select
anchoring
corner
from
Symbol, period and scale can be selected for Chart object. Price scale and date display mode can
also be enabled/disabled.
Example
The following script creates and moves Chart object on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates \"Chart\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Chart";
// Object name
input string
InpSymbol="EURUSD";
// Symbol
input ENUM_TIMEFRAMES
InpPeriod=PERIOD_H1;
// Period
InpScale=2;
// Scale
input bool
InpDateScale=true;
input bool
InpPriceScale=true;
561
InpColor=clrRed;
input ENUM_LINE_STYLE
InpStyle=STYLE_DASHDOTDOT;
input int
InpPointWidth=1;
input bool
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Creating Chart object
//+------------------------------------------------------------------+
bool ObjectChartCreate(const long
chart_ID=0,
// chart's ID
name="Chart",
// object name
const int
sub_window=0,
// subwindow index
const string
symbol="EURUSD",
// symbol
const ENUM_TIMEFRAMES
period=PERIOD_H1,
// period
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const int
width=300,
// width
const int
height=200,
// height
const string
const ENUM_BASE_CORNER
const int
scale=2,
// scale
const bool
date_scale=true,
const bool
price_scale=true,
const color
clr=clrRed,
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
point_width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create Chart object
if(!ObjectCreate(chart_ID,name,OBJ_CHART,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- set object coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set object size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the symbol
562
//+------------------------------------------------------------------+
bool ObjectChartSetSymbolAndPeriod(const long
chart_ID=0,
const string
name="Chart",
// object name
const string
symbol="EURUSD",
// symbol
563
//+------------------------------------------------------------------+
bool ObjectChartMove(const long
chart_ID=0,
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Chart object size
//+------------------------------------------------------------------+
bool ObjectChartChangeSize(const long
chart_ID=0,
width=300,
// width
const int
height=200)
// height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the width of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
564
//+------------------------------------------------------------------+
long ObjectChartGetID(const long
chart_ID=0,
//+------------------------------------------------------------------+
bool ObjectChartDelete(const long
chart_ID=0,
//+------------------------------------------------------------------+
void OnStart()
{
565
symbols=SymbolsTotal(true);
//--- check if the symbol with a specified name is present in the symbol list
bool exist=false;
for(int i=0;i<symbols;i++)
if(InpSymbol==SymbolName(i,true))
{
exist=true;
break;
}
if(!exist)
{
Print("Error! ",InpSymbol," symbol is not present in \"Market Watch\"!");
return;
}
//--- check validity of input parameters
if(InpScale<0 || InpScale>5)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- set Chart object coordinates and its size
int x=(int)x_distance/16;
int y=(int)y_distance/16;
int x_size=(int)x_distance*7/16;
int y_size=(int)y_distance*7/16;
//--- create Chart object
if(!ObjectChartCreate(0,InpName,0,InpSymbol,InpPeriod,x,y,x_size,y_size,InpCorner,InpScale,InpDa
InpPriceScale,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
566
567
OBJ_BITMAP
Bitmap object.
Note
For Bitmap object, you can select visibility scope of an image.
Example
The following script creates several bitmaps on the chart. Special functions have been developed to
create and change graphical object's properties. You can use these functions "as is" in your own
applications.
//--- description
#property description "Script creates a bitmap in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
input int
InpWidth=24;
input int
InpHeight=24;
input int
InpXOffset=4;
input int
InpYOffset=4;
input color
InpColor=clrRed;
input int
InpPointWidth=1;
input bool
InpBack=false;
// Background object
input bool
InpSelection=false;
// Highlight to move
568
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create a bitmap in the chart window
//+------------------------------------------------------------------+
bool BitmapCreate(const long
chart_ID=0,
// chart's ID
const string
name="Bitmap",
// bitmap name
const int
sub_window=0,
// subwindow index
datetime
time=0,
double
price=0,
const string
file="",
const int
width=10,
const int
height=10,
const int
x_offset=0,
const int
y_offset=0,
const color
clr=clrRed,
point_width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- set anchor point coordinates if they are not set
ChangeBitmapEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a bitmap
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create a bitmap in the chart window! Error code = ",GetLastError());
return(false);
}
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- set visibility scope for the image; if width or height values
//--- exceed the width and height (respectively) of a source image,
//--- it is not drawn; in the opposite case,
//--- only the part corresponding to these values is drawn
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the part of an image that is to be displayed in the visibility scope
//--- the default part is the upper left area of an image; the values allow
569
//+------------------------------------------------------------------+
bool BitmapSetImage(const long
chart_ID=0,
// chart's ID
{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move a bitmap in the chart window
//+------------------------------------------------------------------+
bool BitmapMove(const long
chart_ID=0,
// chart's ID
time=0,
double
price=0)
{
//--- if point position is not set, move it to the current bar having Bid price
570
//+------------------------------------------------------------------+
bool BitmapChangeSize(const long
chart_ID=0,
// chart's ID
width=0,
// bitmap width
const int
height=0)
// bitmap height
{
//--- reset the error value
ResetLastError();
//--- change bitmap size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the bitmap width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the bitmap height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Change coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapMoveVisibleArea(const long
chart_ID=0,
// chart's ID
x_offset=0,
const int
y_offset=0)
571
": failed to change X coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a bitmap
//+------------------------------------------------------------------+
bool BitmapDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void ChangeBitmapEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
572
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[];
double
file="\\Images\\dollar.bmp";
573
if(!BitmapCreate(0,"Bitmap_"+(string)i,0,date[i],close[i],InpFile,InpWidth,InpHeight,InpXOffs
InpYOffset,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete Sell signs
for(int i=0;i<bars;i+=step)
{
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--}
574
OBJ_BITMAP_LABEL
Bitmap Label object.
Note
Anchor point position relative to the label can be selected from ENUM_ANCHOR_POINT enumeration.
Anchor point coordinates are set in pixels.
You can also select bitmap anchoring corner from ENUM_BASE_CORNER enumeration.
For bitmap label, you can select visibility scope of an image.
Example
The following script creates several bitmaps on the chart. Special functions have been developed to
create and change graphical object's properties. You can use these functions "as is" in your own
applications.
//--- description
#property description "Script creates \"Bitmap Label\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="BmpLabel";
input string
// Label name
input string
InpFileOff="\\Images\\euro.bmp";
input bool
InpState=false;
// Label pressed/released
input ENUM_BASE_CORNER
InpCorner=CORNER_LEFT_UPPER;
// Anchor type
input color
InpColor=clrRed;
575
InpStyle=STYLE_SOLID;
input int
InpPointWidth=1;
input bool
InpBack=false;
// Background object
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Bitmap Label object
//+------------------------------------------------------------------+
bool BitmapLabelCreate(const long
chart_ID=0,
// chart's ID
const string
name="BmpLabel",
// label name
const int
sub_window=0,
// subwindow index
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const string
file_on="",
// image in On mode
const string
file_off="",
const int
width=0,
const int
height=0,
const int
x_offset=10,
const int
y_offset=10,
const bool
state=false,
// pressed/released
const ENUM_BASE_CORNER
clr=clrRed,
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
point_width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create a bitmap label
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Bitmap Label\" object! Error code = ",GetLastError());
return(false);
}
//--- set the images for On and Off modes
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,0,file_on))
{
Print(__FUNCTION__,
": failed to load the image for On mode! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,1,file_off))
{
576
//+------------------------------------------------------------------+
bool BitmapLabelSetImage(const long
chart_ID=0,
// chart's ID
on_off=0,
577
//+------------------------------------------------------------------+
bool BitmapLabelMove(const long
chart_ID=0,
// chart's ID
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change visibility scope (object) size
//+------------------------------------------------------------------+
bool BitmapLabelChangeSize(const long
chart_ID=0,
// chart's ID
width=0,
// label width
const int
height=0)
// label height
{
//--- reset the error value
ResetLastError();
578
chart_ID=0,
// chart's ID
x_offset=0,
const int
y_offset=0)
{
//--- reset the error value
ResetLastError();
//--- change the object's visibility scope coordinates
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset))
{
Print(__FUNCTION__,
": failed to change X coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete "Bitmap label" object
//+------------------------------------------------------------------+
bool BitmapLabelDelete(const long
chart_ID=0,
// chart's ID
579
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define bitmap label coordinates
int x=(int)x_distance/2;
int y=(int)y_distance/2;
//--- set label size and visibility scope coordinates
int width=32;
int height=32;
int x_offset=0;
int y_offset=0;
//--- place bitmap label at the center of the window
if(!BitmapLabelCreate(0,InpName,0,x,y,InpFileOn,InpFileOff,width,height,x_offset,y_offset,InpSta
InpCorner,InpAnchor,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder)
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change label's visibility scope size in the loop
for(int i=0;i<6;i++)
580
581
OBJ_EDIT
Edit object.
Note
Anchor point coordinates are set in pixels. You can select Edit anchoring corner from
ENUM_BASE_CORNER enumeration.
You can also select one of the text alignment types inside Edit from ENUM_ALIGN_MODE
enumeration.
Example
The following script creates and moves Edit object on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script creates \"Edit\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Edit";
// Object name
input string
InpText="Text";
// Object text
input string
InpFont="Arial";
// Font
input int
InpFontSize=14;
// Font size
input ENUM_ALIGN_MODE
InpAlign=ALIGN_CENTER;
input bool
InpReadOnly=false;
// Permission to edit
InpColor=clrBlack;
// Text color
582
InpBackColor=clrWhite;
// Background color
input color
InpBorderColor=clrBlack;
// Border color
input bool
InpBack=false;
// Background object
input bool
InpSelection=false;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Edit object
//+------------------------------------------------------------------+
bool EditCreate(const long
chart_ID=0,
// chart's ID
const string
name="Edit",
// object name
const int
sub_window=0,
// subwindow index
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const int
width=50,
// width
const int
height=18,
// height
const string
text="Text",
// text
const string
font="Arial",
// font
const int
font_size=10,
// font size
const ENUM_ALIGN_MODE
align=ALIGN_CENTER,
// alignment type
const bool
read_only=false,
// ability to edit
clr=clrBlack,
// text color
const color
back_clr=clrWhite,
// background color
const color
border_clr=clrNONE,
// border color
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create edit field
if(!ObjectCreate(chart_ID,name,OBJ_EDIT,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- set object coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set object size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
583
//+------------------------------------------------------------------+
bool EditMove(const long
chart_ID=0,
// chart's ID
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError());
return(false);
}
584
//+------------------------------------------------------------------+
bool EditChangeSize(const long
chart_ID=0,
// chart's ID
width=0,
// width
const int
height=0)
// height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the object width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the object height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Edit object's text
//+------------------------------------------------------------------+
bool EditTextChange(const long
chart_ID=0,
// chart's ID
585
//+------------------------------------------------------------------+
bool EditTextGet(string
const long
&text,
chart_ID=0,
// text
// chart's ID
//+------------------------------------------------------------------+
bool EditDelete(const long
chart_ID=0,
// chart's ID
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
586
587
588
OBJ_EVENT
Event object.
Note
When hovering mouse over the event, its text appears.
Example
The following script creates and moves Event object on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these functions "as is" in
your own applications.
//--- description
#property description "Script draws \"Event\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="Event";
// Event name
input int
InpDate=25;
// Event date, %
input string
InpText="Text";
// Event text
input color
InpColor=clrRed;
// Event color
input int
InpWidth=1;
input bool
InpBack=false;
// Background event
input bool
input bool
InpHidden=true;
589
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create Event object on the chart
//+------------------------------------------------------------------+
bool EventCreate(const long
chart_ID=0,
// chart's ID
const string
name="Event",
// event name
const int
sub_window=0,
// subwindow index
const string
text="Text",
// event text
datetime
time=0,
// time
const color
clr=clrRed,
// color
const int
width=1,
const bool
back=false,
// in the background
const bool
const bool
hidden=true,
const long
z_order=0)
{
//--- if time is not set, create the object on the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create Event object
if(!ObjectCreate(chart_ID,name,OBJ_EVENT,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- set event text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set anchor point width if the object is highlighted
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving event by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Event object text
//+------------------------------------------------------------------+
590
chart_ID=0,
// chart's ID
// text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Event object
//+------------------------------------------------------------------+
bool EventMove(const long
chart_ID=0,
// chart's ID
time=0)
// time
{
//--- if time is not set, move event to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Event object
//+------------------------------------------------------------------+
bool EventDelete(const long
chart_ID=0,
// chart's ID
591
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- array for storing the date values to be used
//--- for setting and changing Event object anchor point's coordinates
datetime date[];
//--- memory allocation
ArrayResize(date,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- define the points to create an object
int d=InpDate*(bars-1)/100;
//--- create Event object
if(!EventCreate(0,InpName,0,InpText,date[d],InpColor,InpWidth,
InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the object
//--- loop counter
int h_steps=bars/2;
//--- move the object
for(int i=0;i<h_steps;i++)
{
592
593
OBJ_RECTANGLE_LABEL
Rectangle Label object.
Note
Anchor point coordinates are set in pixels. You can select rectangle label's anchoring corner from
ENUM_BASE_CORNER enumeration. Rectangle label's border type can be selected from
ENUM_BORDER_TYPE enumeration.
The object is used to create and design the custom graphical interface.
Example
The following script creates and moves Rectangle Label object on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these functions "as
is" in your own applications.
//--- description
#property description "Script creates \"Rectangle Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string
InpName="RectLabel";
// Label name
input color
InpBackColor=clrSkyBlue;
// Background color
// Border type
InpColor=clrDarkBlue;
input ENUM_LINE_STYLE
InpStyle=STYLE_SOLID;
input int
InpLineWidth=3;
594
InpBack=false;
// Background object
input bool
InpSelection=true;
// Highlight to move
input bool
InpHidden=true;
input long
InpZOrder=0;
//+------------------------------------------------------------------+
//| Create rectangle label
//+------------------------------------------------------------------+
bool RectLabelCreate(const long
chart_ID=0,
// chart's ID
const string
name="RectLabel",
// label name
const int
sub_window=0,
// subwindow index
const int
x=0,
// X coordinate
const int
y=0,
// Y coordinate
const int
width=50,
// width
const int
height=18,
// height
const color
back_clr=C'236,233,216',
// background color
// border type
clr=clrRed,
const ENUM_LINE_STYLE
style=STYLE_SOLID,
const int
line_width=1,
const bool
back=false,
// in the background
const bool
selection=false,
// highlight to move
const bool
hidden=true,
const long
z_order=0)
{
//--- reset the error value
ResetLastError();
//--- create a rectangle label
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create a rectangle label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set label size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border type
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set flat border color (in Flat mode)
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set flat border line style
595
//+------------------------------------------------------------------+
bool RectLabelMove(const long
chart_ID=0,
// chart's ID
x=0,
// X coordinate
const int
y=0)
// Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the rectangle label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the size of the rectangle label
//+------------------------------------------------------------------+
bool RectLabelChangeSize(const long
chart_ID=0,
// chart's ID
width=50,
// label width
const int
height=18)
// label height
596
//+------------------------------------------------------------------+
bool RectLabelChangeBorderType(const long
const string
chart_ID=0,
// chart's ID
name="RectLabel",
// label name
//+------------------------------------------------------------------+
bool RectLabelDelete(const long
chart_ID=0,
// chart's ID
597
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define rectangle label coordinates
int x=(int)x_distance/4;
int y=(int)y_distance/4;
//--- set label size
int width=(int)x_distance/4;
int height=(int)y_distance/4;
//--- create a rectangle label
if(!RectLabelCreate(0,InpName,0,x,y,width,height,InpBackColor,InpBorder,InpCorner,
InpColor,InpStyle,InpLineWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change the size of the rectangle label
int steps=(int)MathMin(x_distance/4,y_distance/4);
for(int i=0;i<steps;i++)
{
//--- resize
width+=1;
height+=1;
if(!RectLabelChangeSize(0,InpName,width,height))
return;
598
599
Object Properties
Graphical objects can have various properties depending on the object type. Values of object
properties are set up and received by corresponding functions for working with graphical objects.
All objects used in technical analysis are bound to the time and price coordinates: trendline, channels,
Fibonacci tools, etc. But there is a number of auxiliary objects intended to improve the user interface
that are bound to the always visible part of a chart (main chart windows or indicator subwindows):
Object
ID
X/Y
Width/
Height
Date/
Price
OBJPR
OP_CO
RNER
OBJPR
OP_AN
CHOR
OBJPR
OP_AN
GLE
Text
OBJ_TEXT
Yes
Yes
Yes
Label
OBJ_LABE
L
Yes
Yes (read
only)
Yes
Yes
Yes
Button
OBJ_BUTT
ON
Yes
Yes
Yes
Bitmap
OBJ_BITM
AP
Yes (read
only)
Yes
Yes
Bitmap
Label
OBJ_BITM
AP_LABEL
Yes
Yes (read
only)
Yes
Yes
Edit
OBJ_EDIT
Yes
Yes
Yes
Rectangle
Label
OBJ_RECT
ANGLE_L
ABEL
Yes
Yes
Yes
ENUM_ANCHOR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
OBJPROP_ANGLE defines the object rotation angle counterclockwise.
The functions defining the properties of graphical objects, as well as ObjectCreate() and ObjectMove()
operations for creating and moving objects along the chart are actually used for sending commands to
the chart. If these functions are executed successfully, the command is included in the common queue
of the chart events. Visual changes in the properties of graphical objects are implemented when
handling the queue of the chart events.
Thus, do not expect an immediate visual update of graphical objects after calling these functions.
600
Description
Property Type
OBJPROP_COLOR
Color
color
OBJPROP_STYLE
Style
ENUM_LINE_STYLE
OBJPROP_WIDTH
Line thickness
int
OBJPROP_BACK
bool
OBJPROP_ZORDER
long
OBJPROP_FILL
bool
OBJPROP_HIDDEN
bool
601
Object is selected
bool
OBJPROP_READONLY
bool
OBJPROP_TYPE
Object type
ENUM_OBJECT r/o
OBJPROP_TIME
Time coordinate
datetime modifier=number of
anchor point
OBJPROP_SELECTABLE
Object availability
bool
OBJPROP_CREATETIME
datetime
OBJPROP_LEVELS
Number of levels
int
OBJPROP_LEVELCOLOR
OBJPROP_LEVELSTYLE
ENUM_LINE_STYLE
modifier=level number
OBJPROP_LEVELWIDTH
int
r/o
modifier=level number
OBJPROP_ALIGN
ENUM_ALIGN_MODE
OBJPROP_FONTSIZE
Font size
int
OBJPROP_RAY_LEFT
bool
OBJPROP_RAY_RIGHT
bool
OBJPROP_RAY
bool
OBJPROP_ELLIPSE
bool
OBJPROP_ARROWCODE
Arrow code
object
char
OBJPROP_TIMEFRAMES
Visibility of
timeframes
OBJPROP_ANCHOR
for the
an
Arrow
object
at
ENUM_ARROW_ANCHOR
OBJ_ARROW),
ENUM_ANCHOR_POINT
OBJ_LABEL,
OBJ_BITMAP_LABEL
OBJ_TEXT)
OBJPROP_XDISTANCE
int
OBJPROP_YDISTANCE
int
(for
(for
and
602
OBJPROP_DEGREE
Level of
Marking
OBJPROP_DRAWLINES
bool
OBJPROP_STATE
Button state
depressed)
bool
OBJPROP_CHART_ID
long r/o
OBJPROP_XSIZE
int
OBJPROP_YSIZE
int
OBJPROP_XOFFSET
int
OBJPROP_YOFFSET
int
the
Elliott
ENUM_GANN_DIRECTION
Wave
(pressed
ENUM_ELLIOT_WAVE_DEGREE
603
Timeframe
object
for
the
Chart
ENUM_TIMEFRAMES
OBJPROP_DATE_SCALE
bool
OBJPROP_PRICE_SCALE
bool
OBJPROP_CHART_SCALE
OBJPROP_BGCOLOR
color
OBJPROP_CORNER
ENUM_BASE_CORNER
OBJPROP_BORDER_TYPE
ENUM_BORDER_TYPE
OBJPROP_BORDER_COLOR
color
When using chart operations for the "Chart" object (OBJ_CHART), the following limitations are
imposed:
It cannot be closed using ChartClose();
Symbol/period cannot be changed using the ChartSetSymbolPeriod() function;
The
following
properties
are
ineffective
CHART_SCALE,
CHART_BRING_TO_TOP,
CHART_SHOW_DATE_SCALE and CHART_SHOW_PRICE_SCALE (ENUM_CHART_PROPERTY_INTEGER).
You can set a special mode of image display for OBJ_BITMAP_LABEL and OBJ_BITMAP objects. In this
mode, only part of an original image (at which a rectangular visible area is applied) is displayed, while
the rest of the image becomes invisible. The size of this area should be set using the properties
OBJPROP_XSIZE and OBJPROP_YSIZE. The visible area can be "moved" only within the original image
using the properties OBJPROP_XOFFSET and OBJPROP_YOFFSET.
604
Description
Property Type
OBJPROP_PRICE
Price coordinate
double
modifier=number of
anchor point
OBJPROP_LEVELVALUE
Level value
double
OBJPROP_SCALE
double
OBJPROP_ANGLE
double
OBJPROP_DEVIATION
double
Standard
modifier=level number
Description
Property Type
OBJPROP_NAME
Object name
string
OBJPROP_TEXT
string
OBJPROP_TOOLTIP
string
OBJPROP_LEVELTEXT
Level description
string
OBJPROP_FONT
Font
string
OBJPROP_BMPFILE
string
modifier: 0-state ON,
1-state OFF
OBJPROP_SYMBOL
string
modifier=level number
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
605
Flat form
BORDER_RAISED
Prominent form
BORDER_SUNKEN
Concave form
For the OBJ_EDIT object ("Edit") and for the ChartScreenShot() function, you can specify the horizontal
alignment type using the values of the ENUM_ALIGN_MODE enumeration.
ENUM_ALIGN_MODE
Identifier
Description
ALIGN_LEFT
Left alignment
ALIGN_CENTER
ALIGN_RIGHT
Right alignment
Example:
#define
UP
"\x0431"
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--string label_name="my_OBJ_LABEL_object";
if(ObjectFind(0,label_name)<0)
{
Print("Object ",label_name," not found. Error code = ",GetLastError());
//--- create Label object
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- 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);
606
607
ID
X/Y
Width/
Height
Date/
Price
OBJPR
OP_CO
RNER
OBJPR
OP_AN
CHOR
OBJPR
OP_AN
GLE
Text
OBJ_TEXT
Yes
Yes
Yes
Label
OBJ_LABE
L
Yes
Yes (read
only)
Yes
Yes
Yes
Button
OBJ_BUTT
ON
Yes
Yes
Yes
Bitmap
OBJ_BITM
AP
Yes (read
only)
Yes
Yes
Bitmap
Label
OBJ_BITM
AP_LABEL
Yes
Yes (read
only)
Yes
Yes
Edit
OBJ_EDIT
Yes
Yes
Yes
Rectangle
Label
OBJ_RECT
ANGLE_L
ABEL
Yes
Yes
Yes
ENUM_ANCHOR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
OBJPROP_ANGLE defines the object rotation angle counterclockwise.
Description
Anchor point at the upper left corner
608
ANCHOR_LEFT_LOWER
ANCHOR_LOWER
ANCHOR_RIGHT_LOWER
ANCHOR_RIGHT
ANCHOR_RIGHT_UPPER
ANCHOR_UPPER
ANCHOR_CENTER
The OBJ_BUTTON, OBJ_RECTANGLE_LABEL, OBJ_EDIT and OBJ_CHART objects have a fixed anchor
point in the upper left corner (ANCHOR_LEFT_UPPER).
Example:
string text_name="my_OBJ_TEXT_object";
if(ObjectFind(0,text_name)<0)
{
Print("Object ",text_name," not found. Error code = ",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Create object Label
ObjectCreate(0,text_name,OBJ_TEXT,0,TimeCurrent(),chart_max_price);
//--- Set color of the text
ObjectSetInteger(0,text_name,OBJPROP_COLOR,clrWhite);
//--- Set background color
ObjectSetInteger(0,text_name,OBJPROP_BGCOLOR,clrGreen);
//--- Set text for the Label object
ObjectSetString(0,text_name,OBJPROP_TEXT,TimeToString(TimeCurrent()));
//--- Set text font
ObjectSetString(0,text_name,OBJPROP_FONT,"Trebuchet MS");
//--- Set font size
ObjectSetInteger(0,text_name,OBJPROP_FONTSIZE,10);
//--- Bind to the upper right corner
ObjectSetInteger(0,text_name,OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
//--- Rotate 90 degrees counter-clockwise
ObjectSetDouble(0,text_name,OBJPROP_ANGLE,90);
//--- Forbid the selection of the object by mouse
ObjectSetInteger(0,text_name,OBJPROP_SELECTABLE,false);
//--- redraw object
ChartRedraw(0);
}
Graphical objects Arrow (OBJ_ARROW) have only 2 ways of linking their coordinates. Identifiers are
listed in ENUM_ARROW_ANCHOR.
ENUM_ARROW_ANCHOR
609
Description
ANCHOR_TOP
ANCHOR_BOTTOM
Example:
void OnStart()
{
//--- Auxiliary arrays
double Ups[],Downs[];
datetime Time[];
//--- Set the arrays as timeseries
ArraySetAsSeries(Ups,true);
ArraySetAsSeries(Downs,true);
ArraySetAsSeries(Time,true);
//--- Create handle of the Indicator Fractals
int FractalsHandle=iFractals(NULL,0);
Print("FractalsHandle = ",FractalsHandle);
//--- Set Last error value to Zero
ResetLastError();
//--- Try to copy the values of the indicator
int copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Print("Unable to copy the upper fractals. Error = ",GetLastError());
return;
}
ResetLastError();
//--- Try to copy the values of the indicator
copied=CopyBuffer(FractalsHandle,1,0,1000,Downs);
if(copied<=0)
{
Print("Unable to copy the bottom fractals. Error = ",GetLastError());
return;
}
ResetLastError();
//--- Copy timeseries containing the opening bars of the last 1000 ones
copied=CopyTime(NULL,0,0,1000,Time);
if(copied<=0)
{
Print("Unable to copy the Opening Time of the last 1000 bars");
return;
}
int upcounter=0,downcounter=0; // count there the number of arrows
bool created;// receive the result of attempts to create an object
610
After the script execution the chart will look like in this figure.
611
612
Object
ID
X/Y
Width/
Height
Date/
Price
OBJPR
OP_CO
RNER
OBJPR
OP_AN
CHOR
OBJPR
OP_AN
GLE
Text
OBJ_TEXT
Yes
Yes
Yes
Label
OBJ_LABE
L
Yes
Yes (read
only)
Yes
Yes
Yes
Button
OBJ_BUTT
ON
Yes
Yes
Yes
Bitmap
OBJ_BITM
AP
Yes (read
only)
Yes
Yes
Bitmap
Label
OBJ_BITM
AP_LABEL
Yes
Yes (read
only)
Yes
Yes
Edit
OBJ_EDIT
Yes
Yes
Yes
Rectangle
Label
OBJ_RECT
ANGLE_L
ABEL
Yes
Yes
Yes
ENUM_ANCHOR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
OBJPROP_ANGLE defines the object rotation angle counterclockwise.
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:
613
enumeration.
ENUM_BASE_CORNER
ID
Description
CORNER_LEFT_UPPER
CORNER_LEFT_LOWER
CORNER_RIGHT_LOWER
CORNER_RIGHT_UPPER
Example:
void CreateLabel(long
chart_id,
string name,
int
chart_corner,
int
anchor_point,
string text_label,
int
x_ord,
int
y_ord)
{
//--if(ObjectCreate(chart_id,name,OBJ_LABEL,0,0,0))
{
ObjectSetInteger(chart_id,name,OBJPROP_CORNER,chart_corner);
ObjectSetInteger(chart_id,name,OBJPROP_ANCHOR,anchor_point);
ObjectSetInteger(chart_id,name,OBJPROP_XDISTANCE,x_ord);
ObjectSetInteger(chart_id,name,OBJPROP_YDISTANCE,y_ord);
ObjectSetString(chart_id,name,OBJPROP_TEXT,text_label);
}
else
Print("Failed to create the object OBJ_LABEL ",name,", Error code = ", GetLastError());
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--int height=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
614
615
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
OBJ_NO_PERIODS
OBJ_PERIOD_M1
0x00000001
OBJ_PERIOD_M2
0x00000002
OBJ_PERIOD_M3
0x00000004
OBJ_PERIOD_M4
0x00000008
OBJ_PERIOD_M5
0x00000010
OBJ_PERIOD_M6
0x00000020
OBJ_PERIOD_M10
0x00000040
OBJ_PERIOD_M12
0x00000080
OBJ_PERIOD_M15
0x00000100
OBJ_PERIOD_M20
0x00000200
OBJ_PERIOD_M30
0x00000400
OBJ_PERIOD_H1
0x00000800
OBJ_PERIOD_H2
0x00001000
OBJ_PERIOD_H3
0x00002000
OBJ_PERIOD_H4
0x00004000
OBJ_PERIOD_H6
0x00008000
616
0x00010000
OBJ_PERIOD_H12
0x00020000
OBJ_PERIOD_D1
0x00040000
OBJ_PERIOD_W1
0x00080000
OBJ_PERIOD_MN1
0x00100000
OBJ_ALL_PERIODS
0x001fffff
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;
double prevLow;
double highs[],lows[];
617
See also
PeriodSeconds, Period, Chart timeframes, Date and Time
618
Description
ELLIOTT_GRAND_SUPERCYCLE
Grand Supercycle
ELLIOTT_SUPERCYCLE
Supercycle
ELLIOTT_CYCLE
Cycle
ELLIOTT_PRIMARY
Primary
ELLIOTT_INTERMEDIATE
Intermediate
ELLIOTT_MINOR
Minor
ELLIOTT_MINUTE
Minute
ELLIOTT_MINUETTE
Minuette
ELLIOTT_SUBMINUETTE
Subminuette
Example:
for(int i=0;i<ObjectsTotal(0);i++)
{
string currobj=ObjectName(0,i);
if((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE3) ||
((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE5)))
{
//--- 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");
}
}
619
Gann Objects
For Gann Fan (OBJ_GANNFAN) and Gann Grid (OBJ_GANNGRID) objects you can specify two values of
the ENUM_GANN_DIRECTION enumeration that sets the trend direction.
ENUM_GANN_DIRECTION
ID
Description
GANN_UP_TREND
GANN_DOWN_TREND
To set the scale of the main line as 1x1, use function ObjectSetDouble(chart_handle,
gann_object_name, OBJPROP_SCALE, scale), where:
chart_handle chart window where the object is located;
gann_object_name object name;
OBJPROP_SCALE identifier of the "Scale" property;
scale required scale in units of Pips/Bar.
620
Time[center_bar/2] = "+(string)Time[c
Time[center_bar/2]="+Time[center_bar/2]);
621
Web Colors
The following color constants are defined for the color type:
clrBlack
clrDarkGre
en
clrDarkSlat
eGray
clrOlive
clrGreen
clrTeal
clrNavy
clrPurple
clrM aroon
clrIndigo
clrM idnigh
tBlue
clrDarkBlu
e
clrDarkOliv
eGreen
clrSaddleB
rown
clrForestG
reen
clrOliveDra
b
clrSeaGre
en
clrDarkGol
denrod
clrDarkSlat
eBlue
clrSienna
clrM edium
Blue
clrBrown
clrDarkTur
quoise
clrDimGray
clrLightSe
aGreen
clrDarkViol
et
clrFireBric
k
clrM edium
VioletRed
clrM edium
SeaGreen
clrChocola
te
clrCrimson
clrSteelBlu
e
clrGoldenr
od
clrM edium
SpringGre
en
clrLawnGr
een
clrCadetBl
ue
clrDarkOrc
hid
clrYellowG
reen
clrLimeGre
en
clrOrange
Red
clrDarkOra
nge
clrOrange
clrGold
clrYellow
clrChartre
use
clrLime
clrSpringG
reen
clrAqua
clrDeepSk
yBlue
clrBlue
clrM agent
a
clrRed
clrGray
clrSlateGra
y
clrPeru
clrBlueViol
et
clrLightSla
teGray
clrDeepPin
k
clrM edium
Turquoise
clrDodgerB
lue
clrTurquoi
se
clrRoyalBlu
e
clrSlateBlu
e
clrDarkKha
ki
clrIndianR
ed
clrM edium
Orchid
clrGreenY
ellow
clrM edium
Aquamarin
e
clrDarkSea
Green
clrTomato
clrRosyBro
wn
clrOrchid
clrM edium
Purple
clrPaleViol
etRed
clrCoral
clrCornflo
werBlue
clrDarkGra
y
clrSandyBr
own
clrM edium
SlateBlue
clrTan
clrDarkSal
mon
clrBurlyWo
od
clrHotPink
clrSalmon
clrViolet
clrLightCor
al
clrSkyBlue
clrLightSal
mon
clrPlum
clrKhaki
clrLightGr
een
clrAquama
rine
clrSilver
clrLightSky
Blue
clrLightSte
elBlue
clrLightBlu
e
clrPaleGre
en
clrThistle
clrPowder
Blue
clrPaleGol
denrod
clrPaleTur
quoise
clrLightGra
y
clrWheat
clrNavajoW
hite
clrM occasi
n
clrLightPin
k
clrGainsbo
ro
clrPeachP
uff
clrPink
clrBisque
clrLightGol
denrod
clrBlanche
dAlmond
clrLemonC
hiffon
clrBeige
clrAntique
White
clrPapaya
Whip
clrCornsilk
clrLightYel
low
clrLightCya
n
clrLinen
clrLavende
r
clrM istyRo
se
clrOldLace
clrWhiteS
moke
clrSeashell
clrIvory
clrHoneyd
ew
clrAliceBlu
e
clrLavend
erBlush
clrM intCre
am
clrSnow
clrWhite
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().
622
#property indicator_type1
DRAW_LINE
#property indicator_type2
DRAW_LINE
#property indicator_type3
DRAW_LINE
#property indicator_color1
clrBlue
#property indicator_color2
clrRed
#property indicator_color3
clrLime
623
Wingdings
Characters of Wingdings used with the OBJ_ARROW object:
// Create an arrow
ObjectSetInteger(0,up_arrow,OBJPROP_ARROWCODE,241);
ObjectSetInteger(0,up_arrow,OBJPROP_TIME,time);
// Set time
}
else
Print("Unable to get the latest Close price!");
}
624
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
625
Price Constants
Calculations of technical indicators require price values and/or values of volumes, on which
calculations will be performed. There are 7 predefined identifiers from the ENUM_APPLIED_PRICE
enumeration, used to specify the desired price base for calculations.
ENUM_APPLIED_PRICE
ID
Description
PRICE_CLOSE
Close price
PRICE_OPEN
Open price
PRICE_HIGH
PRICE_LOW
PRICE_MEDIAN
PRICE_TYPICAL
PRICE_WEIGHTED
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
VOLUME_TICK
Tick volume
VOLUME_REAL
Trade volume
To select a necessary variant for calculation, specify one of the values of the ENUM_STO_PRICE
enumeration.
ENUM_STO_PRICE
ID
Description
STO_LOWHIGH
STO_CLOSECLOSE
If a technical indicator uses for calculations price data, type of which is set by ENUM_APPLIED_PRICE,
then handle of any indicator (built in the terminal or written by a user) can be used as the input price
series. In this case, values of the zero buffer of the indicator will be used for calculations. This makes
it easy to build values of one indicator using values of another indicator. The handle of a custom
indicator is created by calling the iCustom() function.
626
RSIperiod=14;
input int
Smooth=8;
"RSI"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"RSI_Smoothed"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrNavy
#property indicator_style2
STYLE_SOLID
#property indicator_width2
RSIBuffer[];
double
int
RSIhandle;
//+------------------------------------------------------------------+
//| 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[]
)
{
627
ResetLastError();
//--- Get RSI indicator data in an array RSIBuffer []
int copied=CopyBuffer(RSIhandle,0,0,rates_total,RSIBuffer);
if(copied<=0)
{
Print("Unable to copy the values of the indicator RSI. Error = ",
GetLastError(),",
copied =",copied);
return(0);
}
//--- Create the indicator of average values using values of RSI
int RSI_MA_handle=iMA(NULL,0,Smooth,0,meth,RSIhandle);
copied=CopyBuffer(RSI_MA_handle,0,0,rates_total,RSI_SmoothedBuffer);
if(copied<=0)
{
Print("Unable to copy the smoothed indicator of RSI. Error = ",
GetLastError(),",
copied =",copied);
return(0);
}
//--- return value of prev_calculated for next call
return(rates_total);
}
628
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
MODE_SMA
Simple averaging
MODE_EMA
Exponential averaging
MODE_SMMA
Smoothed averaging
MODE_LWMA
Linear-weighted averaging
Example:
double ExtJaws[];
double ExtTeeth[];
double ExtLips[];
//---- handles for moving averages
int
ExtJawsHandle;
int
ExtTeethHandle;
int
ExtLipsHandle;
629
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().
Constant
Value
Description
MAIN_LINE
Main line
SIGNAL_LINE
Signal line
Identifiers of indicator lines permissible when copying values of ADX() and ADXW().
Constant
Value
Description
MAIN_LINE
Main line
PLUSDI_LINE
Line +DI
MINUSDI_LINE
Line DI
Value
Description
BASE_LINE
Main line
UPPER_BAND
Upper limit
LOWER_BAND
Lower limit
Identifiers of indicator lines permissible when copying values of iEnvelopes() and iFractals().
Constant
Value
Description
UPPER_LINE
Upper line
LOWER_LINE
Bottom line
Value
Description
UPPER_HISTOGRAM
Upper histogram
LOWER_HISTOGRAM
Bottom histogram
Value
Description
630
Jaw line
GATORTEETH_LINE
Teeth line
GATORLIPS_LINE
Lips line
Value
Description
TENKANSEN_LINE
Tenkan-sen line
KIJUNSEN_LINE
Kijun-sen line
SENKOUSPANA_LINE
SENKOUSPANB_LINE
CHIKOUSPAN_LINE
631
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 buffers are always bound after value buffers corresponding to the style.
ENUM_DRAW_TYPE
ID
Description
Data buffers
Color buffers
DRAW_NONE
Not drawn
DRAW_LINE
Line
DRAW_SECTION
Section
DRAW_HISTOGRAM
Histogram
zero line
the
DRAW_HISTOGRAM2
DRAW_ARROW
Drawing arrows
DRAW_ZIGZAG
DRAW_FILLING
DRAW_BARS
Display as a sequence
of bars
DRAW_CANDLES
Display as a sequence
of candlesticks
DRAW_COLOR_LINE
Multicolored line
DRAW_COLOR_SECTIO
N
Multicolored section
DRAW_COLOR_HISTO
GRAM
Multicolored histogram
from the zero line
DRAW_COLOR_HISTO
GRAM2
Multicolored histogram
of the two indicator
buffers
from
632
Drawing
arrows
DRAW_COLOR_ZIGZAG
multicolored
Multicolored ZigZag
DRAW_COLOR_BARS
Multicolored bars
DRAW_COLOR_CANDL
ES
Multicolored
candlesticks
To refine the display of the selected drawing type identifiers listed in ENUM_PLOT_PROPERTY are
used.
For functions PlotIndexSetInteger() and PlotIndexGetInteger()
ENUM_PLOT_PROPERTY_INTEGER
ID
Description
Property type
PLOT_ARROW
Arrow
code
DRAW_ARROW
for
style
uchar
PLOT_ARROW_SHIFT
int
PLOT_DRAW_BEGIN
int
PLOT_DRAW_TYPE
ENUM_DRAW_TYPE
PLOT_SHOW_DATA
bool
PLOT_SHIFT
int
PLOT_LINE_STYLE
ENUM_LINE_STYLE
PLOT_LINE_WIDTH
int
PLOT_COLOR_INDEXES
int
PLOT_LINE_COLOR
The index of a
buffer
containing the drawing color
color
modifier = index
number of colors
Description
An empty value for plotting, for
which there is no drawing
Property type
double
633
Description
PLOT_LABEL
Property type
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
STYLE_SOLID
Solid line
STYLE_DASH
Broken line
STYLE_DOT
Dotted line
STYLE_DASHDOT
Dash-dot line
STYLE_DASHDOTDOT
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
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
634
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--for(int i=prev_calculated;i<rates_total;i++)
{
MABuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
635
Description
INDICATOR_DATA
Data to draw
INDICATOR_COLOR_INDEX
Color
INDICATOR_CALCULATIONS
A custom indicator has a lot of settings to provide convenient displaying. These settings are made
through the assignment of corresponding indicator properties using functions IndicatorSetDouble(),
IndicatorSetInteger() and IndicatorSetString(). Identifiers of indicator properties are listed in the
ENUM_CUSTOMIND_PROPERTY enumeration.
ENUM_CUSTOMIND_PROPERTY_INTEGER
ID
Description
Property type
INDICATOR_DIGITS
Accuracy
of
indicator values
drawing
of
int
INDICATOR_HEIGHT
int
INDICATOR_LEVELS
Number of levels
indicator window
int
INDICATOR_LEVELCOLOR
color
level number
INDICATOR_LEVELSTYLE
ENUM_LINE_STYLE modifier =
level number
INDICATOR_LEVELWIDTH
int
level number
in
the
ENUM_CUSTOMIND_PROPERTY_DOUBLE
ID
Description
Property type
INDICATOR_MINIMUM
Minimum
window
of
the
indicator
double
INDICATOR_MAXIMUM
Maximum
window
of
the
indicator
double
modifier =
modifier =
636
Level value
double
level number
modifier =
ENUM_CUSTOMIND_PROPERTY_STRING
ID
Description
Property type
INDICATOR_SHORTNAME
string
INDICATOR_LEVELTEXT
Level description
string
level number
modifier =
Examples:
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots
#property indicator_type1
DRAW_LINE
#property indicator_type2
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_color2
clrRed
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,MainBuffer,INDICATOR_DATA);
SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);
SetIndexBuffer(2,HighesBuffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(3,LowesBuffer,INDICATOR_CALCULATIONS);
//--- set accuracy
IndicatorSetInteger(INDICATOR_DIGITS,2);
//--- set levels
IndicatorSetInteger(INDICATOR_LEVELS,2);
IndicatorSetDouble(INDICATOR_LEVELVALUE,0,20);
IndicatorSetDouble(INDICATOR_LEVELVALUE,1,80);
//--- set maximum and minimum for subwindow
IndicatorSetDouble(INDICATOR_MINIMUM,0);
IndicatorSetDouble(INDICATOR_MAXIMUM,100);
637
638
Indicator
IND_AC
Accelerator Oscillator
IND_AD
Accumulation/Distribution
IND_ADX
IND_ADXW
IND_ALLIGATOR
Alligator
IND_AMA
IND_AO
Awesome Oscillator
IND_ATR
IND_BANDS
Bollinger Bands
IND_BEARS
Bears Power
IND_BULLS
Bulls Power
IND_BWMFI
IND_CCI
IND_CHAIKIN
Chaikin Oscillator
IND_CUSTOM
Custom indicator
IND_DEMA
IND_DEMARKER
DeMarker
IND_ENVELOPES
Envelopes
IND_FORCE
Force Index
IND_FRACTALS
Fractals
IND_FRAMA
IND_GATOR
Gator Oscillator
IND_ICHIMOKU
639
Moving Average
IND_MACD
MACD
IND_MFI
IND_MOMENTUM
Momentum
IND_OBV
On Balance Volume
IND_OSMA
OsMA
IND_RSI
IND_RVI
IND_SAR
Parabolic SAR
IND_STDDEV
Standard Deviation
IND_STOCHASTIC
Stochastic Oscillator
IND_TEMA
IND_TRIX
IND_VIDYA
IND_VOLUMES
Volumes
IND_WPR
640
Data type
TYPE_BOOL
bool
TYPE_CHAR
char
TYPE_UCHAR
uchar
TYPE_SHORT
short
TYPE_USHORT
ushort
TYPE_COLOR
color
TYPE_INT
int
TYPE_UINT
uint
TYPE_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.
641
Environment State
Constants describing the current runtime environment of an mql5-program are divided into groups:
Client terminal properties information about the client terminal;
Executed MQL5-program properties mql5 program properties, which help to control its execution;
Symbol properties obtaining information about a symbol;
Account properties information about the current account;
Testing Statistics results of Expert Advisor testing.
642
Description
Type
TERMINAL_BUILD
The client
number
terminal
build
TERMINAL_COMMUNITY_ACCO
UNT
bool
TERMINAL_COMMUNITY_CONNE
CTION
Connection
MQL5.community
bool
TERMINAL_CONNECTED
bool
TERMINAL_DLLS_ALLOWED
bool
TERMINAL_TRADE_ALLOWED
Permission to trade
bool
TERMINAL_EMAIL_ENABLED
bool
TERMINAL_FTP_ENABLED
bool
TERMINAL_NOTIFICATIONS_EN
ABLED
Permission
to
send
notifications to smartphone
bool
TERMINAL_MAXBARS
int
TERMINAL_MQID
bool
TERMINAL_CODEPAGE
int
TERMINAL_CPU_CORES
int
TERMINAL_DISK_SPACE
int
to
int
643
int
TERMINAL_MEMORY_TOTAL
Memory available
process
of
the
(agent), MB
to the
terminal
int
TERMINAL_MEMORY_AVAILABL
E
int
TERMINAL_MEMORY_USED
int
TERMINAL_X64
Indication
terminal"
bool
TERMINAL_OPENCL_SUPPORT
int
TERMINAL_SCREEN_DPI
int
TERMINAL_PING_LAST
int
of
the
"64-bit
int width
...
//--- Calculating the scaling factor as a percentage
int scale_factor=(TerminalInfoInteger(TERMINAL_SCREEN_DPI) * 100) / 96;
//--- Use of the scaling factor
width=(base_width * scale_factor) / 100;
In the above example, the graphical resource looks the same on monitors with different resolution
characteristics. The size of control elements (buttons, dialog windows, etc.) corresponds to
personalization settings.
644
ENUM_TERMINAL_INFO_DOUBLE
Identifier
Description
TERMINAL_COMMUNITY_BALAN
CE
Type
Balance in MQL5.community
double
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
Identifier
Description
Type
TERMINAL_LANGUAGE
string
TERMINAL_COMPANY
Company name
string
TERMINAL_NAME
Terminal name
string
TERMINAL_PATH
string
TERMINAL_DATA_PATH
string
TERMINAL_COMMONDATA_PAT
H
string
Check_TerminalPaths.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//---
645
As result of the script execution in the Experts Journal you will see a messages, like the following:
646
program,
constants
Description
Type
MQL_MEMORY_LIMIT
int
MQL_MEMORY_USED
int
MQL_PROGRAM_TYPE
ENUM_PROGRAM_TYPE
MQL_DLLS_ALLOWED
bool
MQL_TRADE_ALLOWED
bool
MQL_SIGNALS_ALLOWED
bool
MQL_DEBUG
bool
MQL_PROFILER
bool
MQL_TESTER
bool
MQL_OPTIMIZATION
bool
MQL_VISUAL_MODE
bool
MQL_FRAME_MODE
bool
MQL_LICENSE_TYPE
ENUM_LICENSE_TYPE
from
647
Description
Type
MQL_PROGRAM_NAME
Name of the
executed
mql5-program
string
MQL5_PROGRAM_PATH
string
For 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
ENUM_LICENSE_TYPE
Identifier
Description
LICENSE_FREE
LICENSE_DEMO
LICENSE_FULL
LICENSE_TIME
Example:
ENUM_PROGRAM_TYPE mql_program=(ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL_PROGRAM_TYPE);
switch(mql_program)
{
case PROGRAM_SCRIPT:
{
Print(__FILE__+" is script");
break;
}
case PROGRAM_EXPERT:
{
648
649
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.
For function SymbolInfoInteger()
ENUM_SYMBOL_INFO_INTEGER
Identifier
Description
Type
SYMBOL_SELECT
bool
SYMBOL_SESSION_DEALS
long
SYMBOL_SESSION_BUY_ORDERS
long
SYMBOL_SESSION_SELL_ORDER
S
long
SYMBOL_VOLUME
long
SYMBOL_VOLUMEHIGH
long
SYMBOL_VOLUMELOW
long
SYMBOL_TIME
datetime
SYMBOL_DIGITS
int
SYMBOL_SPREAD_FLOAT
bool
SYMBOL_SPREAD
int
SYMBOL_TICKS_BOOKDEPTH
int
SYMBOL_TRADE_CALC_MODE
ENUM_SYMBOL_CALC_MODE
SYMBOL_TRADE_MODE
ENUM_SYMBOL_TRADE_MODE
SYMBOL_START_TIME
datetime
SYMBOL_EXPIRATION_TIME
datetime
SYMBOL_TRADE_STOPS_LEVEL
int
650
Distance to freeze
operations in points
trade
int
SYMBOL_TRADE_EXEMODE
ENUM_SYMBOL_TRADE_EXECUT
ION
SYMBOL_SWAP_MODE
ENUM_SYMBOL_SWAP_MODE
SYMBOL_SWAP_ROLLOVER3DA
YS
ENUM_DAY_OF_WEEK
SYMBOL_EXPIRATION_MODE
Flags
of
allowed
expiration modes
order
int
SYMBOL_FILLING_MODE
int
SYMBOL_ORDER_MODE
int
SYMBOL_OPTION_MODE
Option type
ENUM_SYMBOL_OPTION_MODE
SYMBOL_OPTION_RIGHT
ENUM_SYMBOL_OPTION_RIGH
T
Description
Type
SYMBOL_BID
double
SYMBOL_BIDHIGH
double
SYMBOL_BIDLOW
double
SYMBOL_ASK
double
SYMBOL_ASKHIGH
double
SYMBOL_ASKLOW
double
SYMBOL_LAST
double
SYMBOL_LASTHIGH
double
SYMBOL_LASTLOW
double
SYMBOL_OPTION_STRIKE
double
SYMBOL_POINT
double
SYMBOL_TRADE_TICK_VALUE
Value
of
double
651
for
double
SYMBOL_TRADE_TICK_VALUE_
LOSS
double
SYMBOL_TRADE_TICK_SIZE
double
SYMBOL_TRADE_CONTRACT_S
IZE
double
SYMBOL_VOLUME_MIN
double
SYMBOL_VOLUME_MAX
double
SYMBOL_VOLUME_STEP
double
SYMBOL_VOLUME_LIMIT
double
SYMBOL_SWAP_LONG
double
SYMBOL_SWAP_SHORT
double
SYMBOL_MARGIN_INITIAL
double
SYMBOL_MARGIN_MAINTENAN
CE
double
652
Summary volume
session deals
current
double
SYMBOL_SESSION_TURNOVER
double
SYMBOL_SESSION_INTEREST
double
SYMBOL_SESSION_BUY_ORDER
S_VOLUME
double
SYMBOL_SESSION_SELL_ORDE
RS_VOLUME
double
SYMBOL_SESSION_OPEN
double
SYMBOL_SESSION_CLOSE
Close price
session
current
double
SYMBOL_SESSION_AW
double
SYMBOL_SESSION_PRICE_SETT
LEMENT
double
SYMBOL_SESSION_PRICE_LIMI
T_MIN
double
SYMBOL_SESSION_PRICE_LIMI
T_MAX
double
SYMBOL_MARGIN_HEDGED
double
of
of
the
Basic calculation:
If
the
initial
margin
(SYMBOL_MARGIN_INITIAL) is
specified for a symbol, the
hedged margin is specified as
an absolute value (in monetary
terms).
If the initial margin is not
specified
(equal to
0),
SYMBOL_MARGIN_HEDGED is
equal to the size of the
contract, that will be used to
calculate the margin by the
653
Description
Type
SYMBOL_BASIS
of
SYMBOL_CURRENCY_BASE
string
SYMBOL_CURRENCY_PROFIT
Profit currency
string
SYMBOL_CURRENCY_MARGIN
Margin currency
string
SYMBOL_BANK
string
SYMBOL_DESCRIPTION
Symbol description
string
SYMBOL_ISIN
The name of a
ISIN
system
Securities
Number). The
Securities
Number
is
alphanumeric
string
symbol in the
(International
Identification
International
Identification
a
12-digit
code
that
string
654
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_SPECIFIED. 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_SPECIFIED is specified for a symbol, then while sending a pending order,
you may specify the moment this pending order is valid till.
Identifier
Value
Description
SYMBOL_EXPIRATION_GTC
SYMBOL_EXPIRATION_DAY
SYMBOL_EXPIRATION_SPECIFIE
D
The
expiration
time
specified in the order
is
SYMBOL_EXPIRATION_SPECIFIE
D_DAY
The
expiration
date
specified in the order
is
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_FOK|SYMBOL_FILLING_IOC. 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.
Fill Policy
Identifier
Value
Description
655
SYMBOL_FILLING_FOK
Immediate or Cancel
SYMBOL_FILLING_IOC
Return
No identifier
In the Request and Instant execution modes the Fill or Kill policy is always used for market orders, and
the Return policy is always used for limit orders. In this case, when sending orders using OrderSend or
OrderSendAsync, there is no need to specify a fill policy for them.
In the Market and Exchange execution modes the Return policy is always allowed for all the order
656
//+------------------------------------------------------------------+
bool IsFillingTypeAllowed(string symbol,int fill_type)
{
//--- Obtain the value of the property that describes allowed filling modes
int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed
return((filling & fill_type)==fill_type);
}
When sending a trade request using OrderSend() function, an order type from ENUM_ORDER_TYPE
enumeration should be specified for some operations. Not all types of orders may be allowed for a
specific symbol. SYMBOL_ORDER_MODE property describes the flags of the allowed order types.
Identifier
Value
Description
SYMBOL_ORDER_MARKET
SYMBOL_ORDER_LIMIT
SYMBOL_ORDER_STOP
SYMBOL_ORDER_STOP_LIMIT
SYMBOL_ORDER_SL
16
SYMBOL_ORDER_TP
32
Example:
//+------------------------------------------------------------------+
//| The function prints out order types allowed for a symbol
//+------------------------------------------------------------------+
void Check_SYMBOL_ORDER_MODE(string symbol)
{
//--- receive the value of the property describing allowed order types
int symbol_order_mode=(int)SymbolInfoInteger(symbol,SYMBOL_ORDER_MODE);
//--- check for market orders (Market Execution)
if((SYMBOL_ORDER_MARKET&symbol_order_mode)==SYMBOL_ORDER_MARKET)
Print(symbol+": Market orders are allowed (Buy and Sell)");
//--- check for Limit orders
657
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
Identifier
Description
Formula
SYMBOL_CALC_MODE_FOREX
Margin: Lots*Contract_Size/
Leverage
Profit:
(close_priceopen_price)
*Contract_Size*Lots
SYMBOL_CALC_MODE_FUTUR
ES
Margin:
Lots
*InitialMargin*Percentage/100
Profit:
(close_priceopen_price)*TickPrice/
TickSize*Lots
SYMBOL_CALC_MODE_CFD
Margin:
Lots
*ContractSize*MarketPrice*Per
centage/100
Profit:
(close_priceopen_price)
*Contract_Size*Lots
SYMBOL_CALC_MODE_CFDIND
EX
Margin:
(Lots*ContractSize*MarketPric
e)*TickPrice/TickSize
Profit:
(close_priceopen_price)
*Contract_Size*Lots
SYMBOL_CALC_MODE_CFDLEV
Margin:
658
(Lots*ContractSize*MarketPric
e*Percentage)/Leverage
Profit:
(close_priceopen_price)
*Contract_Size*Lots
SYMBOL_CALC_MODE_EXCH_
STOCKS
Margin:
Lots*ContractSize*OpenPrice
Profit:
(close_priceopen_price)
*Contract_Size*Lots
SYMBOL_CALC_MODE_EXCH_
FUTURES
Futures mode
calculation of
margin and profit for trading
futures contracts on a stock
exchange
Margin: Lots*InitialMargin or
Lots*MaintenanceMargin
Profit:
(close_priceopen_price)*Lots*TickPrice/
TickSize
SYMBOL_CALC_MODE_EXCH_
FUTURES_FORTS
estimated
(clearing) price of
the
previous session;
o PriceOrder
average
weighted position price or
open price set in the order
(request);
o TickPrice tick price (cost of
the price change by one
point)
o TickSize tick size (minimum
price change step)
Margin: Lots*InitialMargin or
Lots*MaintenanceMargin
Profit:
(close_priceopen_price)*Lots*TickPrice/
TickSize
SYMBOL_CALC_MODE_SERV_C
OLLATERAL
Margin: no
Profit: no
Market Value:
Lots*ContractSize*MarketPric
659
e*LiqudityRate
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
SYMBOL_TRADE_MODE_DISABLED
SYMBOL_TRADE_MODE_LONGONLY
SYMBOL_TRADE_MODE_SHORTONLY
SYMBOL_TRADE_MODE_CLOSEONLY
SYMBOL_TRADE_MODE_FULL
No trade restrictions
for
certain
symbol
are
defined
in
enumeration
ENUM_SYMBOL_TRADE_EXECUTION
Identifier
Description
SYMBOL_TRADE_EXECUTION_REQUEST
Execution by request
SYMBOL_TRADE_EXECUTION_INSTANT
Instant execution
SYMBOL_TRADE_EXECUTION_MARKET
Market execution
SYMBOL_TRADE_EXECUTION_EXCHANGE
Exchange execution
660
Description
SYMBOL_SWAP_MODE_DISABLED
SYMBOL_SWAP_MODE_POINTS
SYMBOL_SWAP_MODE_CURRENCY_SYMBOL
SYMBOL_SWAP_MODE_CURRENCY_MARGIN
SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT
SYMBOL_SWAP_MODE_INTEREST_CURRENT
SYMBOL_SWAP_MODE_INTEREST_OPEN
SYMBOL_SWAP_MODE_REOPEN_CURRENT
SYMBOL_SWAP_MODE_REOPEN_BID
Values of the ENUM_DAY_OF_WEEK enumeration are used for specifying days of week.
ENUM_DAY_OF_WEEK
Identifier
Description
SUNDAY
Sunday
MONDAY
Monday
TUESDAY
Tuesday
WEDNESDAY
Wednesday
THURSDAY
Thursday
FRIDAY
Friday
SATURDAY
Saturday
661
An option is a contract, which gives the right, but not the obligation, to buy or sell an underlying asset
(goods, stocks, futures, etc.) at a specified price on or before a specific date. The following
enumerations describe option properties, including the option type and the right arising from it.
ENUM_SYMBOL_OPTION_RIGHT
Identifier
Description
SYMBOL_OPTION_RIGHT_CALL
SYMBOL_OPTION_RIGHT_PUT
ENUM_SYMBOL_OPTION_MODE
Identifier
Description
SYMBOL_OPTION_MODE_EUROPEAN
SYMBOL_OPTION_MODE_AMERICAN
662
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.
For the function AccountInfoInteger()
ENUM_ACCOUNT_INFO_INTEGER
Identifier
Description
Type
ACCOUNT_LOGIN
Account number
long
ACCOUNT_TRADE_MODE
ENUM_ACCOUNT_TRADE_MODE
ACCOUNT_LEVERAGE
Account leverage
long
ACCOUNT_LIMIT_ORDERS
int
ACCOUNT_MARGIN_SO_MODE
ENUM_ACCOUNT_STOPOUT_MO
DE
ACCOUNT_TRADE_ALLOWED
bool
ACCOUNT_TRADE_EXPERT
bool
ACCOUNT_MARGIN_MODE
ENUM_ACCOUNT_MARGIN_MOD
E
Description
Type
ACCOUNT_BALANCE
double
ACCOUNT_CREDIT
double
ACCOUNT_PROFIT
double
ACCOUNT_EQUITY
double
ACCOUNT_MARGIN
double
ACCOUNT_MARGIN_FREE
double
ACCOUNT_MARGIN_LEVEL
Account
double
margin
level
in
663
double
ACCOUNT_MARGIN_SO_SO
Margin
stop
out
level.
Depending
on
the
set
ACCOUNT_MARGIN_SO_MODE
is expressed in percents or in
the deposit currency
double
ACCOUNT_MARGIN_INITIAL
double
ACCOUNT_MARGIN_MAINTENA
NCE
Maintenance
margin.
The
minimum equity reserved on an
account to cover the minimum
amount of all open positions
double
ACCOUNT_ASSETS
The current
account
an
double
ACCOUNT_LIABILITIES
double
ACCOUNT_COMMISSION_BLOCK
ED
The
current
commission amount
account
double
assets
of
blocked
on an
Description
Type
ACCOUNT_NAME
Client name
string
ACCOUNT_SERVER
string
ACCOUNT_CURRENCY
Account currency
string
ACCOUNT_COMPANY
string
There are several types of accounts that can be opened on a trade server. The type of account on
which an MQL5 program is running can be found out using the ENUM_ACCOUNT_TRADE_MODE
enumeration.
ENUM_ACCOUNT_TRADE_MODE
Identifier
Description
664
Demo account
ACCOUNT_TRADE_MODE_CONTEST
Contest account
ACCOUNT_TRADE_MODE_REAL
Real account
In case equity is not enough for maintaining open positions, the Stop Out situation, i.e. forced closing
occurs. The minimum margin level at which Stop Out occurs can be set in percentage or in monetary
terms. To find out the mode set for the account use the ENUM_ACCOUNT_STOPOUT_MODE
enumeration.
ENUM_ACCOUNT_STOPOUT_MODE
Identifier
Description
ACCOUNT_STOPOUT_MODE_PERCENT
ACCOUNT_STOPOUT_MODE_MONEY
ENUM_ACCOUNT_MARGIN_MODE
Identifier
Description
ACCOUNT_MARGIN_MODE_RETAIL_NETTING
ACCOUNT_MARGIN_MODE_EXCHANGE
ACCOUNT_MARGIN_MODE_RETAIL_HEDGING
//+------------------------------------------------------------------+
void OnStart()
{
//--- Name of the company
string company=AccountInfoString(ACCOUNT_COMPANY);
//--- Name of the client
string name=AccountInfoString(ACCOUNT_NAME);
665
ENUM_ACCOUNT_TRADE_MODE account_type=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_M
//--- Now transform the value of
string trade_mode;
switch(account_type)
{
case
ACCOUNT_TRADE_MODE_DEMO:
trade_mode="demo";
break;
case
ACCOUNT_TRADE_MODE_CONTEST:
trade_mode="contest";
break;
default:
trade_mode="real";
break;
}
//--- Stop Out is set in percentage or money
ENUM_ACCOUNT_STOPOUT_MODE stop_out_mode=(ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoInteger(ACCOUNT_MA
//--- Get the value of the levels when Margin Call and Stop Out occur
double margin_call=AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL);
double stop_out=AccountInfoDouble(ACCOUNT_MARGIN_SO_SO);
//--- Show brief account information
PrintFormat("The account of the client '%s' #%d %s opened in '%s' on the server '%s'",
name,login,trade_mode,company,server);
PrintFormat("Account currency - %s, MarginCall and StopOut levels are set in %s",
currency,(stop_out_mode==ACCOUNT_STOPOUT_MODE_PERCENT)?"percentage":" money");
PrintFormat("MarginCall=%G, StopOut=%G",margin_call,stop_out);
}
666
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
ID
Description of a statistic
parameter
Type
STAT_INITIAL_DEPOSIT
double
STAT_WITHDRAWAL
Money withdrawn
account
an
double
STAT_PROFIT
double
STAT_GROSS_PROFIT
double
STAT_GROSS_LOSS
double
STAT_MAX_PROFITTRADE
double
STAT_MAX_LOSSTRADE
double
STAT_CONPROFITMAX
double
STAT_CONPROFITMAX_TRADES
int
STAT_MAX_CONWINS
double
from
667
int
STAT_CONLOSSMAX
double
STAT_CONLOSSMAX_TRADES
int
STAT_MAX_CONLOSSES
double
STAT_MAX_CONLOSS_TRADES
int
STAT_BALANCEMIN
double
STAT_BALANCE_DD
double
STAT_BALANCEDD_PERCENT
Balance
drawdown
as
a
percentage that was recorded
at the moment of the
maximum balance drawdown in
monetary
terms
(STAT_BALANCE_DD).
double
STAT_BALANCE_DDREL_PERCE
NT
double
STAT_BALANCE_DD_RELATIVE
double
STAT_EQUITYMIN
double
668
double
STAT_EQUITYDD_PERCENT
double
STAT_EQUITY_DDREL_PERCENT
double
STAT_EQUITY_DD_RELATIVE
double
STAT_EXPECTED_PAYOFF
Expected payoff
double
STAT_PROFIT_FACTOR
double
STAT_RECOVERY_FACTOR
double
STAT_SHARPE_RATIO
Sharpe ratio
double
STAT_MIN_MARGINLEVEL
double
STAT_CUSTOM_ONTESTER
double
STAT_DEALS
int
STAT_TRADES
int
STAT_PROFIT_TRADES
Profitable trades
int
669
Losing trades
int
STAT_SHORT_TRADES
Short trades
int
STAT_LONG_TRADES
Long trades
int
STAT_PROFIT_SHORTTRADES
int
STAT_PROFIT_LONGTRADES
int
STAT_PROFITTRADES_AVGCON
int
STAT_LOSSTRADES_AVGCON
int
670
Trade Constants
Various constants used for programming trading strategies are divided into the following groups:
History Database Properties receiving general information on a symbol;
Order properties obtaining information about trade orders;
Position properties obtaining information about current positions;
Deal properties obtaining information about deals;
Trade operation types description of trade operations available;
Trade transaction types - description of possible trade transactions types;
Trade orders in DOM separation of orders according to the direction of a requested operation.
671
Description
Type
SERIES_BARS_COUNT
long
SERIES_FIRSTDATE
datetime
SERIES_LASTBAR_DATE
datetime
SERIES_SERVER_FIRSTDATE
datetime
SERIES_TERMINAL_FIRSTDATE
datetime
SERIES_SYNCHRONIZED
Symbol/period
data
synchronization flag for the
current moment
bool
672
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...().
For functions OrderGetInteger() and HistoryOrderGetInteger()
ENUM_ORDER_PROPERTY_INTEGER
Identifier
Description
Type
ORDER_TIME_SETUP
datetime
ORDER_TYPE
Order type
ENUM_ORDER_TYPE
ORDER_STATE
Order state
ENUM_ORDER_STATE
ORDER_TIME_EXPIRATION
datetime
ORDER_TIME_DONE
datetime
ORDER_TIME_SETUP_MSC
long
ORDER_TIME_DONE_MSC
Order execution/cancellation
time in milliseconds since
01.01.1970
long
ORDER_TYPE_FILLING
ENUM_ORDER_TYPE_FILLING
ORDER_TYPE_TIME
Order lifetime
ENUM_ORDER_TYPE_TIME
ORDER_MAGIC
long
ORDER_POSITION_ID
long
ORDER_POSITION_BY_ID
Identifier of an opposite
position used for closing by
order ORDER_TYPE_CLOSE_BY
long
673
Description
Type
ORDER_VOLUME_INITIAL
double
ORDER_VOLUME_CURRENT
double
ORDER_PRICE_OPEN
double
ORDER_SL
double
ORDER_TP
double
ORDER_PRICE_CURRENT
double
ORDER_PRICE_STOPLIMIT
double
Description
Type
ORDER_SYMBOL
string
ORDER_COMMENT
Order comment
string
ORDER_EXTERNAL_ID
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
ORDER_TYPE_BUY
ORDER_TYPE_SELL
ORDER_TYPE_BUY_LIMIT
ORDER_TYPE_SELL_LIMIT
ORDER_TYPE_BUY_STOP
ORDER_TYPE_SELL_STOP
ORDER_TYPE_BUY_STOP_LIMIT
674
ORDER_TYPE_CLOSE_BY
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
ORDER_STATE_STARTED
ORDER_STATE_PLACED
Order accepted
ORDER_STATE_CANCELED
ORDER_STATE_PARTIAL
ORDER_STATE_FILLED
ORDER_STATE_REJECTED
Order rejected
ORDER_STATE_EXPIRED
Order expired
ORDER_STATE_REQUEST_ADD
ORDER_STATE_REQUEST_MODIFY
Order is being
parameters)
ORDER_STATE_REQUEST_CANCEL
modified
(changing
its
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
ORDER_FILLING_FOK
Description
This filling policy means that an order can be
filled only in the specified amount. If the
necessary amount of a financial instrument is
currently unavailable in the market, the order
will not be executed. The required volume can
be filled using several offers available on the
market at the moment.
675
ORDER_FILLING_RETURN
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
ORDER_TIME_GTC
ORDER_TIME_DAY
ORDER_TIME_SPECIFIED
ORDER_TIME_SPECIFIED_DAY
676
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.
For the function PositionGetInteger()
ENUM_POSITION_PROPERTY_INTEGER
Identifier
Description
Type
POSITION_TIME
datetime
POSITION_TIME_MSC
long
POSITION_TIME_UPDATE
in
long
POSITION_TIME_UPDATE_MSC
long
POSITION_TYPE
Position type
ENUM_POSITION_TYPE
POSITION_MAGIC
long
POSITION_IDENTIFIER
long
POSITION_IDENTIFIER
corresponds
to
MqlTradeRequest::position. If
a position is reversed, the
position identifier changes.
For the function PositionGetDouble()
ENUM_POSITION_PROPERTY_DOUBLE
Identifier
Description
Type
POSITION_VOLUME
Position volume
double
POSITION_PRICE_OPEN
double
POSITION_SL
Stop Loss
level of
opened
double
677
double
POSITION_PRICE_CURRENT
double
POSITION_SWAP
Cumulative swap
double
POSITION_PROFIT
Current profit
double
Description
Type
POSITION_SYMBOL
string
POSITION_COMMENT
Position comment
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
678
Deal Properties
A deal is the reflection of the fact of a trade operation execution based on an order that contains a
trade request. Each trade is described by properties that allow to obtain information about it. In order
to read values of properties, functions of the HistoryDealGet...() type are used, that return values
from corresponding enumerations.
For the function HistoryDealGetInteger()
ENUM_DEAL_PROPERTY_INTEGER
Identifier
Description
Type
DEAL_ORDER
long
DEAL_TIME
Deal time
datetime
DEAL_TIME_MSC
long
DEAL_TYPE
Deal type
ENUM_DEAL_TYPE
DEAL_ENTRY
ENUM_DEAL_ENTRY
DEAL_MAGIC
(see
long
DEAL_POSITION_ID
long
Description
Type
DEAL_VOLUME
Deal volume
double
DEAL_PRICE
Deal price
double
DEAL_COMMISSION
Deal commission
double
DEAL_SWAP
double
DEAL_PROFIT
Deal profit
double
679
Description
Type
DEAL_SYMBOL
Deal symbol
string
DEAL_COMMENT
Deal comment
string
DEAL_EXTERNAL_ID
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_CHARGE
Additional charge
DEAL_TYPE_CORRECTION
Correction
DEAL_TYPE_BONUS
Bonus
DEAL_TYPE_COMMISSION
Additional commission
DEAL_TYPE_COMMISSION_DAILY
Daily commission
DEAL_TYPE_COMMISSION_MONTHLY
Monthly commission
DEAL_TYPE_COMMISSION_AGENT_DAILY
DEAL_TYPE_COMMISSION_AGENT_MONTHLY
DEAL_TYPE_INTEREST
Interest rate
DEAL_TYPE_BUY_CANCELED
DEAL_TYPE_SELL_CANCELED
680
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_OUT
Entry out
DEAL_ENTRY_INOUT
Reverse
DEAL_ENTRY_OUT_BY
681
Description
TRADE_ACTION_DEAL
TRADE_ACTION_PENDING
TRADE_ACTION_SLTP
TRADE_ACTION_MODIFY
TRADE_ACTION_REMOVE
TRADE_ACTION_CLOSE_BY
682
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
To let a programmer to track the actions performed in relation to a trade account,
OnTradeTransaction function has been provided. This handler allows to get trade transactions applied
to an account in MQL5 application. Trade transaction description is submitted in OnTradeTransaction
first parameter using MqlTradeTransaction structure.
Trade transaction type is submitted in the type parameter of MqlTradeTransaction structure. Possible
types of trade transactions are described by the following enumeration:
ENUM_TRADE_TRANSACTION_TYPE
Identifier
Description
TRADE_TRANSACTION_ORDER_ADD
TRADE_TRANSACTION_ORDER_UPDATE
TRADE_TRANSACTION_ORDER_DELETE
683
TRADE_TRANSACTION_DEAL_UPDATE
TRADE_TRANSACTION_DEAL_DELETE
TRADE_TRANSACTION_HISTORY_ADD
TRADE_TRANSACTION_HISTORY_UPDATE
TRADE_TRANSACTION_HISTORY_DELETE
TRADE_TRANSACTION_POSITION
TRADE_TRANSACTION_REQUEST
Depending on a trade transaction type, various parameters are filled in MqlTradeTransaction structure
describing it. A detailed description of submitted data is shown in "Structure of a Trade Transaction".
See also
684
685
Description
BOOK_TYPE_SELL
BOOK_TYPE_BUY
BOOK_TYPE_SELL_MARKET
BOOK_TYPE_BUY_MARKET
See also
Structures and classes, Structure of the DOM, Trade operation types, Market Info
686
Signal Properties
The following enumerations are used when working with trading signals and signal copy settings.
Enumeration of double type properties of the trading signal:
ENUM_SIGNAL_BASE_DOUBLE
ID
Description
SIGNAL_BASE_BALANCE
Account balance
SIGNAL_BASE_EQUITY
Account equity
SIGNAL_BASE_GAIN
Account gain
SIGNAL_BASE_MAX_DRAWDOWN
SIGNAL_BASE_PRICE
SIGNAL_BASE_ROI
Description
SIGNAL_BASE_DATE_PUBLISHED
SIGNAL_BASE_DATE_STARTED
SIGNAL_BASE_ID
Signal ID
SIGNAL_BASE_LEVERAGE
Account leverage
SIGNAL_BASE_PIPS
Profit in pips
SIGNAL_BASE_RATING
Position in rating
SIGNAL_BASE_SUBSCRIBERS
Number of subscribers
SIGNAL_BASE_TRADES
Number of trades
SIGNAL_BASE_TRADE_MODE
Description
SIGNAL_BASE_AUTHOR_LOGIN
Author login
SIGNAL_BASE_BROKER
SIGNAL_BASE_BROKER_SERVER
Broker server
687
Signal name
SIGNAL_BASE_CURRENCY
Description
SIGNAL_INFO_EQUITY_LIMIT
Equity limit
SIGNAL_INFO_SLIPPAGE
SIGNAL_INFO_VOLUME_PERCENT
Description
SIGNAL_INFO_CONFIRMATIONS_DISABLED
SIGNAL_INFO_COPY_SLTP
SIGNAL_INFO_DEPOSIT_PERCENT
SIGNAL_INFO_ID
SIGNAL_INFO_SUBSCRIPTION_ENABLED
SIGNAL_INFO_TERMS_AGREE
Description
Signal name, r/o
See also
Trade signals
synchronization
without
688
Named Constants
All constants used in MQL5 can be divided into the following groups:
Predefined macro substitutions values are substituted during compilation;
Mathematical constants values of some mathematical expressions;
Numerical type constants some of the simple type restrictions;
Uninitialization reason codes description of uninitialization reasons;
Checking Object Pointer enumeration of types of pointers returned by the CheckPointer() function;
Other constants all other constants.
689
Description
__DATE__
__DATETIME__
__LINE__
__FILE__
__PATH__
__FUNCTION__
__FUNCSIG__
__MQLBUILD__, __MQL5BUILD__
Example:
#property copyright "Copyright 2009, MetaQuotes Software Corp."
#property link
"http://www.metaquotes.net"
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
void OnInit()
{
//--- an example of information output at Expert Advisor initialization
Print(" __FUNCTION__ = ",__FUNCTION__,"
__LINE__ = ",__LINE__);
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- an example of information output at Expert Advisor deinitialization
Print(" __FUNCTION__ = ",__FUNCTION__,"
__LINE__ = ",__LINE__);
690
//+------------------------------------------------------------------+
void OnTick()
{
//--- information output at tick receipt
Print(" __MQLBUILD__ = ",__MQLBUILD__,"
__FILE__ = ",__FILE__);
__LINE__ = ",__LINE__);
test1(__FUNCTION__);
test2();
//--}
//+------------------------------------------------------------------+
//| test1
//+------------------------------------------------------------------+
void test1(string par)
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__,"
}
//+------------------------------------------------------------------+
//| test2
//+------------------------------------------------------------------+
void test2()
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__,"
__LINE__ = ",__LINE__);
}
//+------------------------------------------------------------------+
//| OnTimer event handler
//+------------------------------------------------------------------+
void OnTimer()
{
//--Print(" __FUNCTION__ = ",__FUNCTION__,"
__LINE__ = ",__LINE__);
test1(__FUNCTION__);
}
691
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.
Constant
Description
Value
M_E
2.71828182845904523536
M_LOG2E
log2(e)
1.44269504088896340736
M_LOG10E
log10(e)
0.434294481903251827651
M_LN2
ln(2)
0.693147180559945309417
M_LN10
ln(10)
2.30258509299404568402
M_PI
pi
3.14159265358979323846
M_PI_2
pi/2
1.57079632679489661923
M_PI_4
pi/4
0.785398163397448309616
M_1_PI
1/pi
0.318309886183790671538
M_2_PI
2/pi
0.636619772367581343076
M_2_SQRTPI
2/sqrt(pi)
1.12837916709551257390
M_SQRT2
sqrt(2)
1.41421356237309504880
M_SQRT1_2
1/sqrt(2)
0.707106781186547524401
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the values of constants
Print("M_E = ",DoubleToString(M_E,16));
Print("M_LOG2E = ",DoubleToString(M_LOG2E,16));
Print("M_LOG10E = ",DoubleToString(M_LOG10E,16));
Print("M_LN2 = ",DoubleToString(M_LN2,16));
Print("M_LN10 = ",DoubleToString(M_LN10,16));
Print("M_PI = ",DoubleToString(M_PI,16));
Print("M_PI_2 = ",DoubleToString(M_PI_2,16));
Print("M_PI_4 = ",DoubleToString(M_PI_4,16));
Print("M_1_PI = ",DoubleToString(M_1_PI,16));
Print("M_2_PI = ",DoubleToString(M_2_PI,16));
Print("M_2_SQRTPI = ",DoubleToString(M_2_SQRTPI,16));
Print("M_SQRT2 = ",DoubleToString(M_SQRT2,16));
Print("M_SQRT1_2 = ",DoubleToString(M_SQRT1_2,16));
692
693
Description
Value
CHAR_MIN
-128
CHAR_MAX
127
UCHAR_MAX
255
SHORT_MIN
-32768
SHORT_MAX
32767
USHORT_MAX
65535
INT_MIN
-2147483648
INT_MAX
2147483647
UINT_MAX
4294967295
LONG_MIN
-9223372036854775808
LONG_MAX
9223372036854775807
ULONG_MAX
18446744073709551615
DBL_MIN
2.2250738585072014e-308
DBL_MAX
1.7976931348623158e+308
DBL_EPSILON
2.2204460492503131e-016
DBL_DIG
15
694
53
DBL_MAX_10_EXP
308
DBL_MAX_EXP
1024
DBL_MIN_10_EXP
(-307)
DBL_MIN_EXP
(-1021)
FLT_MIN
1.175494351e-38
FLT_MAX
3.402823466e+38
FLT_EPSILON
1.192092896e07
FLT_DIG
FLT_MANT_DIG
24
FLT_MAX_10_EXP
38
FLT_MAX_EXP
128
FLT_MIN_10_EXP
-37
FLT_MIN_EXP
(-125)
Example:
void OnStart()
{
//--- print the constant values
printf("CHAR_MIN = %d",CHAR_MIN);
695
%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);
}
696
Value
Description
REASON_PROGRAM
REASON_REMOVE
REASON_RECOMPILE
REASON_CHARTCHANGE
REASON_CHARTCLOSE
REASON_PARAMETERS
REASON_ACCOUNT
REASON_TEMPLATE
REASON_INITFAILED
REASON_CLOSE
deleted
been
The uninitialization reason code is also passed as a parameter of the predetermined function
OnDeinit(const int reason).
Example:
//+------------------------------------------------------------------+
//| get text description
//+------------------------------------------------------------------+
string getUninitReasonText(int reasonCode)
{
string text="";
//--switch(reasonCode)
{
case REASON_ACCOUNT:
text="Account was changed";break;
697
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- The first way to get the uninitialization reason code
Print(__FUNCTION__,"_Uninitalization reason code = ",reason);
//--- The second way to get the uninitialization reason code
Print(__FUNCTION__,"_UninitReason = ",getUninitReasonText(_UninitReason));
}
698
Description
POINTER_INVALID
Incorrect pointer
POINTER_DYNAMIC
POINTER_AUTOMATIC
See also
Runtime errors, Object Delete Operator delete, CheckPointer
699
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()).
Constant
Description
Value
CHARTS_MAX
The
maximum
possible
number of simultaneously open
charts in the terminal
100
clrNONE
Absence of color
-1
EMPTY_VALUE
DBL_MAX
INVALID_HANDLE
Incorrect handle
-1
IS_DEBUG_MODE
IS_PROFILE_MODE
NULL
WHOLE_ARRAY
-1
WRONG_VALUE
-1
mode,
The EMPTY_VALUE constant usually corresponds to the values of indicators that are not shown in 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
700
//+------------------------------------------------------------------+
ENUM_LINE_STYLE CheckLineStyle(string name)
{
long style;
//--if(ObjectGetInteger(0,name,OBJPROP_STYLE,0,style))
return((ENUM_LINE_STYLE)style);
else
return(WRONG_VALUE);
}
The WHOLE_ARRAY constant is intended for functions that require specifying the number of elements
in processed arrays:
ArrayCopy();
ArrayMinimum();
ArrayMaximum();
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.
IS_PROFILE_MODE constant allows changing a program operation for correct data collection in the
profiling mode. Profiling allows measuring the execution time of the individual program fragments
(usually comprising functions), as well as calculating the number of such calls. Sleep() function calls
can be disabled to determine the execution time in the profiling mode, like in this example:
//--- Sleep can greatly affect (change) profiling result
if(!IS_PROFILE_MODE) Sleep(100); // disabling Sleep() call in the profiling mode
IS_PROFILE_MODE constant value is set by the compiler during the compilation, while it is set to zero
in conventional mode. When launching a program in the profiling mode, a special compilation is
performed and IS_PROFILE_MODE is replaced with a non-zero value.
The IS_DEBUG_MODE constant can be useful when you need to slightly change the operation of a mql5
program in the debugging mode. For example, in debug mode you may need to display additional
debugging information in the terminal log or create additional graphical objects in a chart.
The following example creates a Label object and sets its description and color depending on the script
701
Check_DEBUG_MODE.mq5 |
//|
//|
http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2009, MetaQuotes Software Corp."
#property link
"http://www.metaquotes.net"
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--string label_name="invisible_label";
if(ObjectFind(0,label_name)<0)
{
Print("Object",label_name,"not found. Error code = ",GetLastError());
//--- create Label
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- set X coordinate
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- set Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
ResetLastError();
if(IS_DEBUG_MODE) // debug mode
{
//--- show message about the script execution mode
ObjectSetString(0,label_name,OBJPROP_TEXT,"DEBUG MODE");
//--- set text color to red
if(!ObjectSetInteger(0,label_name,OBJPROP_COLOR,clrRed))
Print("Unable to set the color. Error",GetLastError());
}
else
// operation mode
{
ObjectSetString(0,label_name,OBJPROP_TEXT,"RELEASE MODE");
//--- set text color to invisible
if(!ObjectSetInteger(0,label_name,OBJPROP_COLOR,CLR_NONE))
Print("Unable to set the color. Error ",GetLastError());
}
ChartRedraw();
DebugBreak();
}
}
702
Crypt Methods
The ENUM_CRYPT_METHOD enumeration is used to specify the data transformation method, used in
CryptEncode() and CryptDecode() functions.
ENUM_CRYPT_METHOD
Constant
Description
CRYPT_BASE64
BASE64
CRYPT_AES128
CRYPT_AES256
CRYPT_DES
CRYPT_HASH_SHA1
CRYPT_HASH_SHA256
CRYPT_HASH_MD5
CRYPT_ARCH_ZIP
ZIP archives
See also
See also
DebugBreak, Executed MQL5 program properties, CryptEncode(), CryptDecode()
703
Data Structures
MQL5 Language offers 8 predefined structures:
MqlDateTime is intended for working with date and time;
MqlParam can send input parameters when creating a handle of the indicator using the
IndicatorCreate() function;
MqlRates is intended for manipulating the historical data, it contains information about the price,
704
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;
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
TimeToStruct, Structures and Classes
705
type;
long
integer_value;
double
double_value;
string
string_value;
};
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.
706
MqlRates
This structure stores information about the prices, volumes and spread.
struct MqlRates
{
datetime time;
double
open;
// Open price
double
high;
double
low;
double
close;
// Close price
long
tick_volume;
// Tick volume
int
spread;
// Spread
long
real_volume;
// Trade volume
};
Example:
void OnStart()
{
MqlRates rates[];
int copied=CopyRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Error copying price data ",GetLastError());
else Print("Copied ",ArraySize(rates)," bars");
}
See also
CopyRates, Access to timeseries
707
MqlBookInfo
It provides information about the market depth data.
struct MqlBookInfo
{
ENUM_BOOK_TYPE
type;
double
price;
// Price
long
volume;
// Volume
};
Note
The MqlBookInfo structure is predefined, thus it doesn't require any declaration and description. To
use the structure, just declare a variable of this type.
The DOM is available only for some symbols.
Example:
MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo about ",Symbol());
}
else
{
Print("Failed to receive DOM for the symbol ",Symbol());
}
See also
MarketBookAdd, MarketBookRelease, MarketBookGet, Trade Orders in DOM, Data Types
708
action;
ulong
magic;
ulong
order;
// Order ticket
string
symbol;
// Trade symbol
double
volume;
double
price;
// Price
double
stoplimit;
double
sl;
double
tp;
ulong
deviation;
ENUM_ORDER_TYPE
type;
// Order type
ENUM_ORDER_TYPE_FILLING
type_filling;
ENUM_ORDER_TYPE_TIME
type_time;
datetime
expiration;
string
comment;
// Order comment
ulong
position;
// Position ticket
ulong
position_by;
};
Fields description
Field
Description
action
magic
order
symbol
volume
709
price
stoplimit
sl
tp
deviation
type
Order
type.
Can
be
one
of
ENUM_ORDER_TYPE enumeration values.
type_filling
type_time
expiration
comment
Order comment
position
position_by
orders
the
of
When modifying or closing a position in the hedging system, make sure to specify its ticket
(MqlTradeRequest::ticket). The ticket can also be specified in the netting system, though a
position is identified by the symbol name.
For sending orders to perform trade operations it is necessary to use the 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
710
711
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
See also
Structures and Classes, Trade Functions, Order Properties
712
retcode;
// Reply code
double
balance;
double
equity;
double
profit;
// Floating profit
double
margin;
// Margin requirements
double
margin_free;
// Free margin
double
margin_level;
// Margin level
string
comment;
};
Description of Fields
Field
Description
retcode
Return code
balance
equity
profit
margin
margin_free
margin_level
comment
See also
Trade Request Structure, Structure for Current Prices, OrderSend, OrderCheck
713
retcode;
ulong
deal;
ulong
order;
double
volume;
double
price;
double
bid;
double
ask;
string
comment;
uint
request_id;
};
Fields description
Field
Description
retcode
deal
order
volume
price
bid
ask
comment
request_id
The trade operation result is returned to a variable of the MqlTradeResult type, which is passed as the
second parameter to OrderSend() to perform trade operations.
714
sent by the terminal to the trade server, while the request itself and its request_id are stored in the
terminal memory;
the trade request execution result as MqlTradeResult structure with request_id field containing ID of
this request.
OnTradeTransaction() function receives three input parameters but the last two should be analyzed
only for transactions having TRADE_TRANSACTION_REQUEST type. In all other cases, data on the trade
request and its execution result are not filled. Example of parameters analysis can be found at
Structure of a Trade Request.
Setting request_id by the terminal for the trade request when sending it to the server is mainly
introduced for working with OrderSendAsync() asynchronous function. This identifier allows to
associate the performed action (OrderSend or OrderSendAsync functions call) with the result of this
action sent to OnTradeTransaction().
Example:
//+------------------------------------------------------------------+
//| Sending a trade request with the result processing
//+------------------------------------------------------------------+
bool MyOrderSend(MqlTradeRequest request,MqlTradeResult result)
{
//--- reset the last error code to zero
ResetLastError();
//--- send request
bool success=OrderSend(request,result);
//--- if the result fails - try to find out why
if(!success)
{
int answer=result.retcode;
Print("TradeLog: Trade request failed. Error = ",GetLastError());
switch(answer)
{
//--- requote
case 10004:
{
Print("TRADE_RETCODE_REQUOTE");
Print("request.price = ",request.price,"
result.ask = ",
715
result.ask = ",
result.ask = ",
result.volume = ",
result.volume);
break;
}
//--- not enough money for a trade operation
case 10019:
{
Print("TRADE_RETCODE_NO_MONEY");
Print("request.volume = ",request.volume,"
result.volume,"
result.volume = ",
result.comment = ",result.comment);
break;
}
//--- some other reason, output the server response code
default:
{
Print("Other answer = ",answer);
}
}
//--- notify about the unsuccessful result of the trade request by returning false
return(false);
}
//--- OrderSend() returns true - repeat the answer
return(true);
716
717
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
Special OnTradeTransaction() handler is provided in MQL5 to get trade transactions applied to an
account. The first parameter of the handler gets MqlTradeTransaction structure describing trade
transactions.
struct MqlTradeTransaction
{
ulong
deal;
// Deal ticket
ulong
order;
// Order ticket
string
symbol;
ENUM_TRADE_TRANSACTION_TYPE
type;
ENUM_ORDER_TYPE
order_type;
// Order type
ENUM_ORDER_STATE
order_state;
// Order state
ENUM_DEAL_TYPE
deal_type;
// Deal type
ENUM_ORDER_TYPE_TIME
time_type;
datetime
time_expiration;
double
price;
// Price
double
price_trigger;
double
price_sl;
double
price_tp;
double
volume;
// Volume in lots
ulong
position;
// Position ticket
ulong
position_by;
};
Fields Description
718
Field
Description
deal
Deal ticket.
order
Order ticket.
symbol
type
order_type
order_state
deal_type
type_time
time_expiration
price
price_trigger
price_sl
price_tp
volume
position
position_by
of
price
and
The essential parameter for received transaction analysis is its type specified in type field. For
example, if a transaction is of TRADE_TRANSACTION_REQUEST type (a result of handling a trade
719
and
ORDER_TYPE_SELL_STOP_LIMIT);
price_sl - Stop Loss order price (filled, if specified in the order);
price_tp - Take Profit order price (filled, if specified in the order);
volume - order current volume (unfilled). Initial order volume can be found in the orders history
execution. It is only filled for market orders, not filled for TRADE_TRANSACTION_ORDER_ADD.
position_by - the ticket of the opposite position. It is only filled for the close by orders (to close a
720
performed);
price_tp - Take Profit price (filled, if specified in the order, based on which a deal has been
performed);
volume - deal volume in lots.
position - the ticket of the position that was opened, modified or closed as a result of deal
execution.
position_by - the ticket of the opposite position. It is only filled for the out by deals (closing a
Position change (adding, changing or closing), as a result of a deal execution, does not lead to
the occurrence of TRADE_TRANSACTION_POSITION transaction.
TRADE_TRANSACTION_REQUEST
Only one field in MqlTradeTransaction structure is filled for trade transactions describing the fact
that a trade request has been processed by a server and processing result has been received
(TRADE_TRANSACTION_REQUEST):
type - trade transaction type;
Only type field (trade transaction type) must be analyzed for such transactions. The second and
third parameters of OnTradeTransaction function (request and result) must be analyzed for
additional data.
Example:
input int MagicNumber=1234567;
//--- enable CTrade trading class and declare the variable of this class
#include <Trade\Trade.mqh>
CTrade trade;
//--- flags for installing and deleting the pending order
bool pending_done=false;
bool pending_deleted=false;
//--- pending order ticket will be stored here
ulong order_ticket;
//+------------------------------------------------------------------+
//| Expert initialization function
721
//+------------------------------------------------------------------+
void OnTick()
{
//---installing a pending order
if(!pending_done)
{
double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double buy_stop_price=NormalizeDouble(ask+1000*_Point,(int)SymbolInfoInteger(_Symbol,SYMBOL_D
bool res=trade.BuyStop(0.1,buy_stop_price,_Symbol);
//--- if BuyStop() function performed successfully
if(res)
{
pending_done=true;
//--- get a result of the request sending from ctrade
MqlTradeResult trade_result;
trade.Result(trade_result);
//--- get request_id for the sent request
uint request_id=trade_result.request_id;
Print("Request has been sent to set a pending order. Request_ID=",request_id);
//--- storing the order ticket (will be zero if using the asynchronous mode of sending to
order_ticket=trade_result.order;
//--- all is done, early exit from OnTick() handler
return;
}
}
//--- delete the pending order
if(!pending_deleted)
//--- additional check
if(pending_done && (order_ticket!=0))
{
//--- trying to delete the pending order
bool res=trade.OrderDelete(order_ticket);
Print("OrderDelete=",res);
//--- when delete request is sent successfully
if(res)
722
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
//--- get transaction type as enumeration value
ENUM_TRADE_TRANSACTION_TYPE type=(ENUM_TRADE_TRANSACTION_TYPE)trans.type;
//--- if the transaction is the request handling result, only its name is displayed
if(type==TRADE_TRANSACTION_REQUEST)
{
Print(EnumToString(type));
//--- display the handled request string name
Print("------------RequestDescription\r\n",RequestDescription(request));
//--- display request result description
Print("------------ResultDescription\r\n",TradeResultDescription(result));
//--- store the order ticket for its deletion at the next handling in OnTick()
if(result.order!=0)
{
//--- delete this order by its ticket at the next OnTick() call
order_ticket=result.order;
Print(" Pending order ticket ",order_ticket,"\r\n");
}
}
else // display the full description for transactions of another type
//--- display description of the received transaction in the Journal
Print("------------TransactionDescription\r\n",TransactionDescription(trans));
//--}
//+------------------------------------------------------------------+
723
//+------------------------------------------------------------------+
string TransactionDescription(const MqlTradeTransaction &trans)
{
//--string desc=EnumToString(trans.type)+"\r\n";
desc+="Symbol: "+trans.symbol+"\r\n";
desc+="Deal ticket: "+(string)trans.deal+"\r\n";
desc+="Deal type: "+EnumToString(trans.deal_type)+"\r\n";
desc+="Order ticket: "+(string)trans.order+"\r\n";
desc+="Order type: "+EnumToString(trans.order_type)+"\r\n";
desc+="Order state: "+EnumToString(trans.order_state)+"\r\n";
desc+="Order time type: "+EnumToString(trans.time_type)+"\r\n";
desc+="Order expiration: "+TimeToString(trans.time_expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",trans.price)+"\r\n";
desc+="Price trigger: "+StringFormat("%G",trans.price_trigger)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",trans.price_sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",trans.price_tp)+"\r\n";
desc+="Volume: "+StringFormat("%G",trans.volume)+"\r\n";
desc+="Position: "+(string)trans.position+"\r\n";
desc+="Position by: "+(string)trans.position_by+"\r\n";
//--- return the obtained string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the trade request textual description
//+------------------------------------------------------------------+
string RequestDescription(const MqlTradeRequest &request)
{
//--string desc=EnumToString(request.action)+"\r\n";
desc+="Symbol: "+request.symbol+"\r\n";
desc+="Magic Number: "+StringFormat("%d",request.magic)+"\r\n";
desc+="Order ticket: "+(string)request.order+"\r\n";
desc+="Order type: "+EnumToString(request.type)+"\r\n";
desc+="Order filling: "+EnumToString(request.type_filling)+"\r\n";
desc+="Order time type: "+EnumToString(request.type_time)+"\r\n";
desc+="Order expiration: "+TimeToString(request.expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",request.price)+"\r\n";
desc+="Deviation points: "+StringFormat("%G",request.deviation)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",request.sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",request.tp)+"\r\n";
desc+="Stop Limit: "+StringFormat("%G",request.stoplimit)+"\r\n";
desc+="Volume: "+StringFormat("%G",request.volume)+"\r\n";
desc+="Comment: "+request.comment+"\r\n";
//--- return the obtained string
return desc;
}
//+------------------------------------------------------------------+
724
//+------------------------------------------------------------------+
string TradeResultDescription(const MqlTradeResult &result)
{
//--string desc="Retcode "+(string)result.retcode+"\r\n";
desc+="Request ID: "+StringFormat("%d",result.request_id)+"\r\n";
desc+="Order ticket: "+(string)result.order+"\r\n";
desc+="Deal ticket: "+(string)result.deal+"\r\n";
desc+="Volume: "+StringFormat("%G",result.volume)+"\r\n";
desc+="Price: "+StringFormat("%G",result.price)+"\r\n";
desc+="Ask: "+StringFormat("%G",result.ask)+"\r\n";
desc+="Bid: "+StringFormat("%G",result.bid)+"\r\n";
desc+="Comment: "+result.comment+"\r\n";
//--- return the obtained string
return desc;
}
See also
Trade Transaction Types, OnTradeTransaction()
725
time;
double
bid;
double
ask;
double
last;
ulong
volume;
long
time_msc;
uint
flag
// Tick flags
};
The variable of the MqlTick type allows obtaining values of Ask, Bid, Last and Volume within a single
call of the SymbolInfoTick() function.
The parameters of each tick are filled in regardless of whether there are changes compared to the
previous tick. Thus, it is possible to find out a correct price for any moment in the past without the
need to search for previous values at the tick history. For example, even if only a Bid price changes
during a tick arrival, the structure still contains other parameters as well, including the previous Ask
price, volume, etc.
You can analyze the tick flags to find out what data have been changed exactly:
TICK_FLAG_BID tick has changed a Bid price
TICK_FLAG_ASK a tick has changed an Ask price
TICK_FLAG_LAST a tick has changed the last deal price
TICK_FLAG_VOLUME a tick has changed a volume
TICK_FLAG_BUY a tick is a result of a buy deal
TICK_FLAG_SELL a tick is a result of a sell deal
Example:
void OnTick()
{
MqlTick last_tick;
//--if(SymbolInfoTick(Symbol(),last_tick))
{
Print(last_tick.time,": Bid = ",last_tick.bid,
" Ask = ",last_tick.ask,"
Volume = ",last_tick.volume);
}
else Print("SymbolInfoTick() failed, error = ",GetLastError());
//--}
See also
Structures and Classes, CopyTicks(), SymbolInfoTick()
2000-2016, MetaQuotes Software Corp.
726
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 execution of mql5-programs, which can be obtained using the
GetLastError() function.
727
Constant
Description
10004
TRADE_RETCODE_REQUOTE
Requote
10006
TRADE_RETCODE_REJECT
Request rejected
10007
TRADE_RETCODE_CANCEL
10008
TRADE_RETCODE_PLACED
Order placed
10009
TRADE_RETCODE_DONE
Request completed
10010
TRADE_RETCODE_DONE_PARTI
AL
10011
TRADE_RETCODE_ERROR
10012
TRADE_RETCODE_TIMEOUT
10013
TRADE_RETCODE_INVALID
Invalid request
10014
TRADE_RETCODE_INVALID_VOL
UME
10015
TRADE_RETCODE_INVALID_PRI
CE
10016
TRADE_RETCODE_INVALID_STO
PS
10017
TRADE_RETCODE_TRADE_DISA
BLED
Trade is disabled
10018
TRADE_RETCODE_MARKET_CL
OSED
Market is closed
10019
TRADE_RETCODE_NO_MONEY
10020
TRADE_RETCODE_PRICE_CHAN
GED
Prices changed
10021
TRADE_RETCODE_PRICE_OFF
10022
TRADE_RETCODE_INVALID_EXPI
RATION
10023
TRADE_RETCODE_ORDER_CHA
NGED
10024
TRADE_RETCODE_TOO_MANY_
REQUESTS
728
TRADE_RETCODE_NO_CHANGE
S
No changes in request
10026
TRADE_RETCODE_SERVER_DISA
BLES_AT
10027
TRADE_RETCODE_CLIENT_DISA
BLES_AT
10028
TRADE_RETCODE_LOCKED
10029
TRADE_RETCODE_FROZEN
10030
TRADE_RETCODE_INVALID_FILL
10031
TRADE_RETCODE_CONNECTION
10032
TRADE_RETCODE_ONLY_REAL
10033
TRADE_RETCODE_LIMIT_ORDE
RS
10034
TRADE_RETCODE_LIMIT_VOLU
ME
10035
TRADE_RETCODE_INVALID_ORD
ER
10036
TRADE_RETCODE_POSITION_CL
OSED
729
Compiler Warnings
Compiler warnings are shown for informational purposes only and are not error messages.
Code
Description
21
22
23
24
25
26
29
Enumeration already defined (duplication) members will be added to the first definition
30
Overriding macro
31
32
33
34
35
36
37
38
41
43
730
44
45
46
47
48
49
50
51
52
53
54
'OnInit' function
parameters
55
56
'OnDeinit' function is
parameters
57
58
59
60
61
62
63
64
65
This variable
variable
is
defined
with
defined with
declaration
hides
wrong
wrong
predefined
731
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
732
86
87
733
Compilation Errors
MetaEdtior 5 shows error messages about the program errors detected by the built-in compiler during
compilation. The list of these errors is given below in table. To compile a source code into an
executable one, press F7. Programs that contain errors cannot be compiled until the errors identified
by the compiler are eliminated.
Code
Description
100
101
103
104
105
106
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
734
124
125
126
127
128
129
130
131
132
133
134
135
136
137
Variable is expected
138
140
141
142
143
144
145
146
147
149
150
151
152
Operator is expected
153
Misuse of break
154
155
156
735
157
Expression is expected
158
159
160
161
162
163
164
165
166
167
168
170
Value is expected
171
172
173
Integer is expected
174
175
176
177
178
179
180
181
182
183
184
736
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
208
209
210
211
213
214
737
216
218
219
220
221
222
223
Operand expected
224
225
226
227
228
229
230
232
235
236
237
238
239
Syntax error
240
241
242
243
244
738
245
246
247
248
249
250
251
252
253
256
Undeclared identifier
257
258
260
261
262
263
264
265
266
267
268
269
270
271
272
739
274
276
277
278
279
280
281
284
285
286
287
288
289
290
291
293
294
295
296
297
298
299
Must be a class
300
302
Type mismatch
303
304
740
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
741
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
the
742
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
Inconsistent #ifdef/#endif
373
374
375
OnTesterInit() impossible
OnTesterDeinit()
376
377
to
use
are not
without
743
378
379
380
Not used
381
382
383
744
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.
Constant
Code
Description
ERR_SUCCESS
The
operation
successfully
ERR_INTERNAL_ERROR
4001
ERR_WRONG_INTERNAL_PARA
METER
4002
ERR_INVALID_PARAMETER
4003
ERR_NOT_ENOUGH_MEMORY
4004
ERR_STRUCT_WITHOBJECTS_
ORCLASS
4005
ERR_INVALID_ARRAY
4006
ERR_ARRAY_RESIZE_ERROR
4007
ERR_STRING_RESIZE_ERROR
4008
ERR_NOTINITIALIZED_STRING
4009
ERR_INVALID_DATETIME
4010
ERR_ARRAY_BAD_SIZE
4011
ERR_INVALID_POINTER
4012
Wrong pointer
ERR_INVALID_POINTER_TYPE
4013
ERR_FUNCTION_NOT_ALLOWE
D
4014
ERR_RESOURCE_NAME_DUPLIC
ATED
4015
ERR_RESOURCE_NOT_FOUND
4016
completed
745
ERR_RESOURCE_UNSUPPOTED
_TYPE
4017
ERR_RESOURCE_NAME_IS_TO
O_LONG
4018
ERR_CHART_WRONG_ID
4101
Wrong chart ID
ERR_CHART_NO_REPLY
4102
ERR_CHART_NOT_FOUND
4103
ERR_CHART_NO_EXPERT
4104
ERR_CHART_CANNOT_OPEN
4105
ERR_CHART_CANNOT_CHANG
E
4106
ERR_CHART_WRONG_PARAME
TER
4107
ERR_CHART_CANNOT_CREATE
_TIMER
4108
ERR_CHART_WRONG_PROPER
TY
4109
ERR_CHART_SCREENSHOT_FAI
LED
4110
ERR_CHART_NAVIGATE_FAILE
D
4111
ERR_CHART_TEMPLATE_FAILE
D
4112
ERR_CHART_WINDOW_NOT_F
OUND
4113
Subwindow containing
indicator was not found
ERR_CHART_INDICATOR_CANN
OT_ADD
4114
ERR_CHART_INDICATOR_CANN
OT_DEL
4115
Error deleting an
from the chart
ERR_CHART_INDICATOR_NOT_
FOUND
4116
ERR_OBJECT_ERROR
4201
ERR_OBJECT_NOT_FOUND
4202
Charts
the
indicator
Graphical Objects
746
ERR_OBJECT_WRONG_PROPER
TY
4203
ERR_OBJECT_GETDATE_FAILE
D
4204
Unable
to
get
date
corresponding to the value
ERR_OBJECT_GETVALUE_FAIL
ED
4205
Unable
to
get
value
corresponding to the date
ERR_MARKET_UNKNOWN_SYM
BOL
4301
Unknown symbol
ERR_MARKET_NOT_SELECTED
4302
ERR_MARKET_WRONG_PROPE
RTY
4303
ERR_MARKET_LASTTIME_UNKN
OWN
4304
ERR_MARKET_SELECT_ERROR
4305
ERR_HISTORY_NOT_FOUND
4401
ERR_HISTORY_WRONG_PROPE
RTY
4402
Wrong ID
property
ERR_GLOBALVARIABLE_NOT_F
OUND
4501
ERR_GLOBALVARIABLE_EXISTS
4502
ERR_MAIL_SEND_FAILED
4510
ERR_PLAY_SOUND_FAILED
4511
ERR_MQL5_WRONG_PROPERT
Y
4512
Wrong identifier
program property
of
the
ERR_TERMINAL_WRONG_PROP
ERTY
4513
Wrong identifier
terminal property
of
the
ERR_FTP_SEND_FAILED
4514
ERR_NOTIFICATION_SEND_FAI
LED
4515
ERR_NOTIFICATION_WRONG_P
ARAMETER
4516
MarketInfo
in
History Access
of
the
history
Global_Variables
747
passed
to
the
SendNotification() function
ERR_NOTIFICATION_WRONG_S
ETTINGS
4517
Wrong
settings
of
notifications in the terminal
(ID is not specified or
permission is not set)
ERR_NOTIFICATION_TOO_FRE
QUENT
4518
Too frequent
notifications
ERR_FTP_NOSERVER
4519
ERR_FTP_NOLOGIN
4520
ERR_FTP_FILE_ERROR
4521
ERR_FTP_CONNECT_FAILED
4522
ERR_FTP_CHANGEDIR
4523
ERR_FTP_CLOSED
4524
ERR_BUFFERS_NO_MEMORY
4601
ERR_BUFFERS_WRONG_INDEX
4602
4603
Wrong ID of the
indicator property
ERR_ACCOUNT_WRONG_PROP
ERTY
4701
ERR_TRADE_WRONG_PROPER
TY
4751
ERR_TRADE_DISABLED
4752
ERR_TRADE_POSITION_NOT_F
OUND
4753
ERR_TRADE_ORDER_NOT_FOU
ND
4754
ERR_TRADE_DEAL_NOT_FOUN
D
4755
ERR_TRADE_SEND_FAILED
4756
sending
of
custom
Account
748
Indicators
ERR_INDICATOR_UNKNOWN_S
YMBOL
4801
Unknown symbol
ERR_INDICATOR_CANNOT_CRE
ATE
4802
ERR_INDICATOR_NO_MEMORY
4803
ERR_INDICATOR_CANNOT_APP
LY
4804
ERR_INDICATOR_CANNOT_ADD
4805
ERR_INDICATOR_DATA_NOT_F
OUND
4806
ERR_INDICATOR_WRONG_HAN
DLE
4807
ERR_INDICATOR_WRONG_PAR
AMETERS
4808
ERR_INDICATOR_PARAMETERS
_MISSING
4809
ERR_INDICATOR_CUSTOM_NA
ME
4810
ERR_INDICATOR_PARAMETER_
TYPE
4811
ERR_INDICATOR_WRONG_INDE
X
4812
ERR_BOOKS_CANNOT_ADD
4901
ERR_BOOKS_CANNOT_DELETE
4902
ERR_BOOKS_CANNOT_GET
4903
ERR_BOOKS_CANNOT_SUBSCRI
BE
4904
5001
Depth of Market
File Operations
ERR_TOO_MANY_FILES
749
ERR_WRONG_FILENAME
5002
ERR_TOO_LONG_FILENAME
5003
ERR_CANNOT_OPEN_FILE
5004
ERR_FILE_CACHEBUFFER_ERR
OR
5005
ERR_CANNOT_DELETE_FILE
5006
ERR_INVALID_FILEHANDLE
5007
ERR_WRONG_FILEHANDLE
5008
ERR_FILE_NOTTOWRITE
5009
ERR_FILE_NOTTOREAD
5010
ERR_FILE_NOTBIN
5011
ERR_FILE_NOTTXT
5012
ERR_FILE_NOTTXTORCSV
5013
ERR_FILE_NOTCSV
5014
ERR_FILE_READERROR
5015
ERR_FILE_BINSTRINGSIZE
5016
ERR_INCOMPATIBLE_FILE
5017
ERR_FILE_IS_DIRECTORY
5018
ERR_FILE_NOT_EXIST
5019
ERR_FILE_CANNOT_REWRITE
5020
ERR_WRONG_DIRECTORYNAM
E
5021
ERR_DIRECTORY_NOT_EXIST
5022
ERR_FILE_ISNOT_DIRECTORY
5023
ERR_CANNOT_DELETE_DIRECT
5024
The
directory
cannot
be
750
ORY
removed
ERR_CANNOT_CLEAN_DIRECT
ORY
5025
ERR_FILE_WRITEERROR
5026
ERR_FILE_ENDOFFILE
5027
ERR_NO_STRING_DATE
5030
ERR_WRONG_STRING_DATE
5031
ERR_WRONG_STRING_TIME
5032
ERR_STRING_TIME_ERROR
5033
ERR_STRING_OUT_OF_MEMOR
Y
5034
ERR_STRING_SMALL_LEN
5035
ERR_STRING_TOO_BIGNUMBER
5036
ERR_WRONG_FORMATSTRING
5037
ERR_TOO_MANY_FORMATTER
S
5038
ERR_TOO_MANY_PARAMETERS
5039
ERR_WRONG_STRING_PARAME
TER
5040
ERR_STRINGPOS_OUTOFRANG
E
5041
ERR_STRING_ZEROADDED
5042
ERR_STRING_UNKNOWNTYPE
5043
ERR_WRONG_STRING_OBJECT
5044
String Casting
when
751
5050
ERR_SMALL_ASSERIES_ARRAY
5051
ERR_SMALL_ARRAY
5052
ERR_ZEROSIZE_ARRAY
5053
ERR_NUMBER_ARRAYS_ONLY
5054
ERR_ONEDIM_ARRAYS_ONLY
5055
Must be a one-dimensional
array
ERR_SERIES_ARRAY
5056
ERR_DOUBLE_ARRAY_ONLY
5057
ERR_FLOAT_ARRAY_ONLY
5058
ERR_LONG_ARRAY_ONLY
5059
ERR_INT_ARRAY_ONLY
5060
ERR_SHORT_ARRAY_ONLY
5061
ERR_CHAR_ARRAY_ONLY
5062
ERR_OPENCL_NOT_SUPPORTE
D
5100
ERR_OPENCL_INTERNAL
5101
ERR_OPENCL_INVALID_HANDL
E
5102
ERR_OPENCL_CONTEXT_CREA
TE
5103
Error creating
context
ERR_OPENCL_QUEUE_CREATE
5104
ERR_OPENCL_PROGRAM_CREA
TE
5105
ERR_OPENCL_TOO_LONG_KER
NEL_NAME
5106
the
OpenCL
752
ERR_OPENCL_KERNEL_CREATE
5107
Error creating
kernel
an
OpenCL
ERR_OPENCL_SET_KERNEL_PA
RAMETER
5108
ERR_OPENCL_EXECUTE
5109
ERR_OPENCL_WRONG_BUFFER
_SIZE
5110
ERR_OPENCL_WRONG_BUFFER
_OFFSET
5111
ERR_OPENCL_BUFFER_CREATE
5112
ERR_WEBREQUEST_INVALID_A
DDRESS
5200
Invalid URL
ERR_WEBREQUEST_CONNECT_
FAILED
5201
ERR_WEBREQUEST_TIMEOUT
5202
Timeout exceeded
ERR_WEBREQUEST_REQUEST_
FAILED
5203
65536
User-Defined Errors
ERR_USER_ERROR_FIRST
See also
Trade Server Return Codes
753
754
Value
Description
FILE_READ
FILE_WRITE
FILE_BIN
Binary
read/write
mode
(without string to string
conversion). Flag is used in
FileOpen().
FILE_CSV
FILE_TXT
16
FILE_ANSI
32
FILE_UNICODE
64
FILE_SHARE_READ
128
FILE_SHARE_WRITE
256
755
512
FILE_COMMON
4096
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
756
File Properties
The FileGetInteger() function is used for obtaining file properties. The identifier of the required
property from the ENUM_FILE_PROPERTY_INTEGER enumeration is passed to it during call.
ENUM_FILE_PROPERTY_INTEGER
ID
ID description
FILE_EXISTS
FILE_CREATE_DATE
Date of creation
FILE_MODIFY_DATE
FILE_ACCESS_DATE
FILE_SIZE
FILE_POSITION
FILE_END
FILE_LINE_END
FILE_IS_COMMON
FILE_IS_TEXT
FILE_IS_BINARY
FILE_IS_CSV
FILE_IS_ANSI
FILE_IS_READABLE
FILE_IS_WRITABLE
The FileGetInteger() function has two different options of call. In the first option, for getting
properties of a file, its handle is specified, which is obtained while opening the file using the
FileOpen() function. This option allows getting all properties of a file.
The second option of the FileGetInteger() function returns values of file properties by the file name.
Using this option, only the following general properties can be obtained:
FILE_EXISTS existence of a file with a specified name
FILE_CREATE_DATE date of creation of the file with the specified name
FILE_MODIFY_DATE date of modification of the file with the specified name
FILE_ACCESS_DATE date of the last access to the file with the specified name
FILE_SIZE size of the file with the specified name
When trying to get properties other than specified above, the second option of FileGetInteger() call
will return an error.
757
Description
SEEK_SET
File beginning
SEEK_CUR
SEEK_END
File end
See also
FileIsEnding, FileIsLineEnding
758
Value
Description
CP_ACP
CP_OEMCP
CP_MACCP
CP_THREAD_ACP
CP_SYMBOL
42
CP_UTF7
65000
CP_UTF8
65001
See also
Client Terminal Properties
ANSI
759
Value
Description
IDOK
IDCANCEL
"Cancel"
pressed
IDABORT
"Abort"
pressed
IDRETRY
"Retry"
pressed
IDIGNORE
"Ignore"
pressed
IDYES
IDNO
IDTRYAGAIN
10
IDCONTINUE
11
button
has
been
button
has
been
button
has
been
has
been
button
The main flags of the MessageBox() function define contents and behavior of the dialog window. This
value can be a combination of the following flag groups:
Constant
Value
Description
MB_OK
0x00000000
MB_OKCANCEL
0x00000001
MB_ABORTRETRYIGNORE
0x00000002
MB_YESNOCANCEL
0x00000003
MB_YESNO
0x00000004
760
MB_RETRYCANCEL
0x00000005
MB_CANCELTRYCONTINUE
0x00000006
Value
Description
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND
0x00000010
MB_ICONQUESTION
0x00000020
MB_ICONEXCLAMATION,
MB_ICONWARNING
0x00000030
MB_ICONINFORMATION,
MB_ICONASTERISK
0x00000040
Value
Description
MB_DEFBUTTON1
0x00000000
The
first
button
MB_DEFBUTTON1 - is default,
if
the
other
buttons
MB_DEFBUTTON2,
MB_DEFBUTTON3,
or
MB_DEFBUTTON4
are
not
specified
MB_DEFBUTTON2
0x00000100
MB_DEFBUTTON3
0x00000200
MB_DEFBUTTON4
0x00000300
761
MQL5 programs
MQL5 Programs
For the mql5-program to operate, it must be compiled (Compile button or F7 key). Compilation should
pass without errors (some warnings are possible; they should be analyzed). At this process, an
executable file with the same name and with EX5 extension must be created in the corresponding
directory, terminal_dir\MQL5\Experts, terminal_dir\MQL5\indicators or terminal_dir\MQL5\scripts.
This file can be run.
Operating features of MQL5 programs are described in the following sections:
Program running order of calling predefined event-handlers.
Testing trading strategies operating features of MQL5 programs in the Strategy Tester.
Client terminal events description of events, which can be processed in programs.
Call of imported functions description order, allowed parameters, search details and call agreement
Expert Advisors, custom indicators and scripts are attached to one of opened charts by Drag'n'Drop
method from the Navigator window.
For an expert Advisor to stop operating, it should be removed from a chart. To do it select "Expert
list" in chart context menu, then select an Expert Advisor from list and click "Remove" button.
Operation of Expert Advisors is also affected by the state of the "AutoTrading" button.
In order to stop a custom indicator, it should be removed from a chart.
Custom indicators and Expert Advisors work until they are explicitly removed from a chart;
information about attached Expert Advisors and Indicators is saved between client terminal sessions.
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.
762
MQL5 programs
Program Running
Each script and each Expert Advisor runs in its own separate thread. All indicators calculated on one
symbol, even if they are attached to different charts, work in the same thread. Thus, all indicators on
one symbol share the resources of one thread.
All other actions associated with a symbol, like processing of ticks and history synchronization, are
also consistently performed in the same thread with indicators. This means that if an infinite action is
performed in an indicator, all other events associated with its symbol will never be performed.
When running an Expert Advisor, make sure that it has an actual trading environment and can access
the history of the required symbol and period, and synchronize data between the terminal and the
server. For all these procedures, the terminal provides a start delay of no more than 5 seconds, after
which the Expert Advisor will be started with available data. Therefore, in case there is no connection
to the server, this may lead to a delay in the start of an Expert Advisor.
The below table contains a brief summary of MQL5 programs:
Program
Running
Note
Script
Expert Advisor
Indicator
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
have at least one event-handler, otherwise the loaded program will not be executed. Event handlers
have predefined names, parameters and return types.
Type
Function name
Parameters
Application
Comment
int
OnInit
none
Expert Advisors
and indicators
Init
event
handler. It allows
to use the void
return type.
void
OnDeinit
Expert Advisors
and indicators
Deinit
handler.
event
void
OnStart
none
scripts
Start
event
763
MQL5 programs
handler.
int
OnCalculate
const
int
rates_total,
const
int
prev_calculated,
const datetime
&Time[],
const
double
&Open[],
const
double
&High[],
const
double
&Low[],
const
double
&Close[],
const
long
&TickVolume[],
const
long
&Volume[],
const
int
&Spread[]
indicators
Calculate
event
handler for all
prices.
int
OnCalculate
const
int
rates_total,
const
int
prev_calculated,
const int begin,
const
double
&price[]
indicators
Calculate event
handler on the
single
data
array.
Indicator cannot
have two event
handlers
simultaneously.
In this case the
only one event
handler will work
on
the
data
array.
void
OnTick
none
Expert Advisors
NewTick
event
handler.
While
the event of a
new tick receipt
is
being
processed,
no
other events of
this type are
received.
void
OnTimer
none
Expert Advisors
and indicators
Timer
handler.
event
void
OnTrade
none
Expert Advisors
Trade
handler.
event
764
MQL5 programs
double
OnTester
none
Expert Advisors
Tester
handler.
event
void
OnChartEvent
Expert Advisors
and indicators
ChartEvent event
handler.
void
OnBookEvent
const
string
&symbol_name
Expert Advisors
and indicators
BookEvent event
handler.
A client terminal sends new events to the corresponding open charts. Events can also be generated by
charts (chart events) or mql5-programs (custom events). Generation of events of creation or deletion
of graphical objects on a chart can be enabled or disabled by setting CHART_EVENT_OBJECT_CREATE
and CHART_EVENT_OBJECT_DELETE chart properties. Each MQL5 program and each chart has its own
queue of events, where all new incoming events are added.
A program receives only events from the chart it runs on. All events are processed one after another in
the order they are received. If a queue already has a NewTick event, or this event is currently being
processed, then the new NewTick event is not placed in the queue of the MQL5 program. Similarly, if
ChartEvent is already enqueued, or this event is being processed, no new event of this kind is
enqueued. The timer events are handled the same way if the Timer event is in the queue or being
handled, the new timer event is not enqueued.
Event queues have a limited but sufficient size, so that the queue overflow for well written programs
is unlikely. In case of queue overflow, new events are discarded without queuing.
It is not recommended to use infinite loops to handle events. The exception to this rule may be only
scripts that process only a single Start event.
Libraries do not handle any events.
765
MQL5 programs
MessageBox().
All functions designed for indicators are prohibited in Expert Advisors and scripts:
SetIndexBuffer();
IndicatorSetDouble();
IndicatorSetInteger();
IndicatorSetString();
PlotIndexSetDouble();
PlotIndexSetInteger();
PlotIndexSetString();
PlotIndexGetInteger.
The library is not an independent program and is executed in the context of the MQL5 program that
has called it: script, indicator or Expert Advisor. Accordingly, the above restrictions apply to the called
library.
766
MQL5 programs
when attaching an Expert Advisor to a chart;
terminal start (if the Expert Advisor was attached to the chart prior to the shutdown of the
terminal);
loading of a template (if the Expert Advisor attached to the chart is specified in the template);
change of a profile (if the Expert Advisor is attached to the one of the profile charts);
connection to an account, even if the account number is the same (if the Expert Advisor was attached
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.
TestExpert.mq5 |
//|
//|
https://www.mql5.com |
767
MQL5 programs
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
class CTestClass
{
public:
CTestClass() { Print("CTestClass constructor"); }
~CTestClass() { Print("CTestClass destructor"); }
};
CTestClass global;
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--Print("Initialization");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--Print("Deinitialization with reason",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
//--}
//+------------------------------------------------------------------+
See also
Client terminal events, Event handlers
768
MQL5 programs
Trade Permission
Trade Automation
MQL5 language provides a special group of trade functions designed for developing automated trading
systems. Programs developed for automated trading with no human intervention are called Expert
Advisors or trading robots. In order to create an Expert Advisor in MetaEditor, launch MQL5 Wizard
and select one of the two options:
Expert Advisor (template) allows you to create a template with ready-made event handling
functions that should be supplemented with all necessary functionality by means of programming.
Expert Advisor (generate) allows you to develop a full-fledged trading robot simply by selecting the
necessary modules: trading signals module, money management module and trailing stop module.
Trading functions can work only in Expert Advisors and scripts. Trading is not allowed for indicators.
769
MQL5 programs
You can switch automated trading option right on the terminal's Standard panel:
Sample check:
if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");
770
MQL5 programs
Sample check:
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");
else
{
if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
Alert("Automated trading is forbidden in the program settings for ",__FILE__);
}
Checking if trading is allowed for any Expert Advisors/scripts for the current
account
Automated trading can be disabled at the trade server side. Sample check:
if(!AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
Alert("Automated trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN),
" at the trade server side");
If automated trading is disabled for a trading account, trading operations of Expert Advisors/scripts
are not executed.
771
MQL5 programs
".\n Perhaps an investor password has been used to connect to the trading account.",
"\n Check the terminal journal for the following entry:",
connection
to
the
trade
server.
TerminalInfoInteger(TERMINAL_CONNECTED);
That
can
be
checked
See also
Client Terminal Properties, Account Properties, Properties of a Running MQL5 Program
using
772
MQL5 programs
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 sent 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.
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.
773
MQL5 programs
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:
sending, modifying or removing of a pending order;
cancellation of a pending order with not enough of money or expiration;
activation of a pending order;
opening, adding or closing a position (or part of the position);
modifying of the open position (change stops Stop Loss and/or Take Profit).
TradeTransaction
When performing some definite actions on a trade account, its state changes. Such actions include:
Sending a trade request from any MQL5 application in the client terminal using OrderSend and
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions. Arrival of such a transaction at the terminal is a
TradeTransaction event. This event is handled by OnTradeTransaction function.
Tester
The Tester event is generated after testing of an Expert Advisor on history data is over. The event is
handled by the OnTester() function.
774
MQL5 programs
TesterInit
The TesterInit event is generated with the start of optimization in the strategy tester before the first
optimization pass. The TesterInit event is handled by the OnTesterInit() function.
TesterPass
The TesterPass event is generated when a new data frame is received. The TesterPass event is
handled by the OnTesterPass() function.
TesterDeinit
The TesterDeinit event is generated after the end of optimization of an Expert Advisor in the strategy
tester. The TesterDeinit event is handled by the OnTesterDeinit() function.
ChartEvent
The ChartEvent event is generated by the client terminal when a user is working with a chart:
keystroke, when the chart window is in focus;
graphical object created
graphical object deleted
mouse press on the graphical object of the chart
move of the graphical object using the mouse
end of text editing in LabelEdit.
Also there is a custom event ChartEvent, which can be sent to an Expert Advisor by any mql5 program
by using the EventChartCustom function. The event is processed by the OnChartEvent function.
BookEvent
The BookEvent event is generated by the client terminal after the Depth Of Market is changed; it is
processed by the OnBookEvent function. To start generation of BookEvent for the specified symbol, it
is necessary to subscribe the symbol to this event by using the MarketBookAdd function.
To unsubscribe from BookEvent for a specified symbol, it is necessary to call the MarketBookRelease
function. The BookEvent event is a broadcasting-type event - it means that it is sufficient to subscribe
just one Expert Advisor for this event, and all other Expert Advisors that have the OnBookEvent event
handler, will receive it. That's why it is necessary to analyze the symbol name, which is passed to a
handler as a parameter.
See also
Event handlers, Program running
775
MQL5 programs
Resources
Using graphics and sound in MQL5 programs
Programs in MQL5 allow working with sound and graphic files:
PlaySound() plays a sound file;
ObjectCreate()
allows
OBJ_BITMAP_LABEL.
OBJ_BITMAP and
PlaySound()
Example of call of the PlaySound() function:
//+------------------------------------------------------------------+
//| Calls standard OrderSend() and plays a sound
//+------------------------------------------------------------------+
void OrderSendWithAudio(MqlTradeRequest
{
//--- send a request to a server
OrderSend(request,result);
//--- if a request is accepted, play sound Ok.wav
if(result.retcode==TRADE_RETCODE_PLACED) PlaySound("Ok.wav");
//--- if fails, play alarm from file timeout.wav
else PlaySound("timeout.wav");
}
The example shows how to play sounds from files 'Ok.wav' and 'timeout.wav', which are included into
the standard terminal package. These files are located in the folder terminal_directory\Sounds.
Here terminal_directory is a folder, from which the MetaTrader 5 Client Terminal is started. The
location of the terminal directory can be found out from an mql5 program in the following way:
//--- Folder, in which terminal data are stored
string terminal_path=TerminalInfoString(TERMINAL_PATH);
You can use sound files not only from the folder terminal_directory\Sounds, but also from any
subfolder located in terminal_data_directory\MQL5. You can find out the location of the terminal
data directory from the terminal menu "File" -> "Open Data Folder" or using program method:
//--- Folder, in which terminal data are stored
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
For example, if the Demo.wav sound file is located in terminal_data_directory\MQL5\Files, then call of
PlaySound() should be written the following way:
//--- play Demo.wav from the folder terminal_directory_data\MQL5\Files\
PlaySound("\\Files\\Demo.wav");
Please note that in the comment the path to the file is written using backslash "\", and in the function
"\\" is used.
776
MQL5 programs
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.
Call PlaySound() function with NULL parameter to stop playback:
//--- call of PlaySound() with NULL parameter stops playback
PlaySound(NULL);
ObjectCreate()
Example of an Expert Advisor, which creates a graphical label (OBJ_BITMAP_LABEL) using the
ObjectCreate() function.
string label_name="currency_label";
string euro
="\\Images\\euro.bmp";
string dollar
="\\Images\\dollar.bmp";
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- create a button OBJ_BITMAP_LABEL, if it hasn't been created yet
if(ObjectFind(0,label_name)<0)
{
//--- trying to create object OBJ_BITMAP_LABEL
bool created=ObjectCreate(0,label_name,OBJ_BITMAP_LABEL,0,0,0);
if(created)
{
//--- link the button to the left upper corner of the chart
ObjectSetInteger(0,label_name,OBJPROP_CORNER,CORNER_RIGHT_UPPER);
//--- now set up the object properties
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,50);
//--- reset the code of the last error to 0
ResetLastError();
//--- download a picture to indicate the "Pressed" state of the button
bool set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,0,euro);
//--- test the result
if(!set)
{
777
MQL5 programs
{
//--- send a command for a chart to refresh so that the button appears immediately without
ChartRedraw(0);
}
else
{
//--- failed to create an object, notify
PrintFormat("Failed to create object OBJ_BITMAP_LABEL. Error code %d",GetLastError());
}
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete an object from a chart
ObjectDelete(0,label_name);
}
Creation and setup of the graphical object named currency_label are carried out in the OnInit()
function. The paths to the graphical files are set in global variables euro and dollar, a double backlash
is used for a separator:
string euro
="\\Images\\euro.bmp";
string dollar
="\\Images\\dollar.bmp";
778
MQL5 programs
The size of the button with a graphical interface is automatically adjusted to the size of the picture.
The image is changed by a left mouse button click on the OBJ_BITMAP_LABEL object ("Disable
selection" option must be checked 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.
The #resource command tells the compiler that the resource at the specified path
path_to_resource_file should be included into the executable EX5 file. Thus all the necessary images
and sounds can be located directly in an EX5 file, so that there is no need to transfer separately the
files used in it, if you want to run the program on a different terminal. Any EX5 file can contain
resources, and any EX5 program can use resources from another EX5 program.
The files in format BMP and WAV are automatically compressed before including them to an EX5 file.
This denotes that in addition to the creation of complete programs in MQL5, using resources also
allows to reduce the total size of necessary files when using graphics and sounds, as compared to the
usual way of MQL5 program writing.
The resource file size must not exceed 16 Mb.
779
MQL5 programs
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
#resource "Resource\\map.bmp"
#resource "..\\picture_3.bmp"
Use of Resources
Resource name
After a resource is declared using the #resource directive, it can be used in any part of a program. The
name of the resource is its path without a backslash at the beginning of the line, which sets the path
to the resource. To use your own resource in the code, the special sign "::" should be added before the
resource name.
Examples:
//--- examples of resource specification and their names in comments
#resource "\\Images\\euro.bmp"
#resource "picture.bmp"
#resource "Resource\\map.bmp"
#resource "\\Sounds\\thrill.wav";
...
//--- utilization of resources
780
MQL5 programs
ObjectSetString(0,bitmap_name,OBJPROP_BMPFILE,0,"::Images\\euro.bmp");
...
ObjectSetString(0,my_bitmap,OBJPROP_BMPFILE,0,"::picture.bmp");
...
set=ObjectSetString(0,bitmap_label,OBJPROP_BMPFILE,1,"::Files\\Pictures\\good.bmp");
...
PlaySound("::Files\\Demo.wav");
...
PlaySound("::Sounds\\thrill.wav");
It should be noted that when setting images from a resource to the OBJ_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.
#resource "\\Images\\euro.bmp";
#resource "\\Images\\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:
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.
781
MQL5 programs
//--- using the resource in the script
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"::Files\\triangle.bmp");
In order to use the same resource from another program, e.g. from an Expert Advisor, we need to add
to the resource name the path to the EX5 file relative to terminal_data_directory\MQL5\ and the
name of the script's EX5 file - Draw_Triangles_Script.ex5. Suppose the script is located in the
standard folder terminal_data_directory\MQL5\Scripts\, then the call should be written the following
way:
//--- using a resource from a script in an EA
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"\\Scripts\\Draw_Triangles_Script.ex5::Files\\tr
If the path to the executable file is not specified when calling the resource from another EX5, the
executable file is searched for in the same folder that contains the program that calls the resource.
This means that if an Expert Advisor calls a resource from Draw_Triangles_Script.ex5 without
specification of the path, like this:
//--- call script resource in an EA without specifying the path
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"Draw_Triangles_Script.ex5::Files\\triangle.bmp"
then the file will be searched for in the folder terminal_data_directory\MQL5\Experts\, if the Expert
Advisor is located in terminal_data_directory\MQL5\Experts\.
SampleEA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#resource "\\Indicators\\SampleIndicator.ex5"
int handle_ind;
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--handle_ind=iCustom(_Symbol,_Period,"::Indicators\\SampleIndicator.ex5");
if(handle_ind==INVALID_HANDLE)
{
Print("Expert: iCustom call: Error code=",GetLastError());
return(INIT_FAILED);
782
MQL5 programs
}
//--- ...
return(INIT_SUCCEEDED);
}
The case when a custom indicator in OnInit() function creates one or more copies of itself requires
special consideration. Please keep in mind that the resource should be specified in the following way:
<path_EX5_file_name>::<resource_name>.
For example, if SampleIndicator.ex5 indicator is included to SampleEA.ex5 Expert Advisor as a
resource, the path to itself specified when calling iCustom() in the custom indicator's initialization
function looks the following way: "\\Experts\\SampleEA.ex5::Indicators\\SampleIndicator.ex5". When
this path is set explicitly, SampleIndicator.ex5 custom indicator is rigidly connected to SampleEA.ex5
Expert Advisor losing ability to work independently.
The path to itself can be received using GetRelativeProgramPath() function. The example of its usage
is provided below:
//+------------------------------------------------------------------+
//|
SampleIndicator.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_plots 0
int handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- the wrong way to provide a link to itself
//--- string path="\\Experts\\SampleEA.ex5::Indicators\\SampleIndicator.ex5";
//--- the right way to receive a link to itself
string path=GetRelativeProgramPath();
//--- indicator buffers mapping
handle=iCustom(_Symbol,_Period,path,0,0);
if(handle==INVALID_HANDLE)
{
Print("Indicator: iCustom call: Error code=",GetLastError());
return(INIT_FAILED);
}
else Print("Indicator handle=",handle);
//--return(INIT_SUCCEEDED);
}
///....
//+------------------------------------------------------------------+
//| GetRelativeProgramPath
//+------------------------------------------------------------------+
783
MQL5 programs
string GetRelativeProgramPath()
{
int pos2;
//--- get the absolute path to the application
string path=MQLInfoString(MQL_PROGRAM_PATH);
//--- find the position of "\MQL5\" substring
int
pos =StringFind(path,"\\MQL5\\");
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double& price[])
{
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
ResourceCreate(), ResourceSave(), PlaySound(), ObjectSetInteger(), ChartApplyTemplate(), File
Functions
784
MQL5 programs
785
MQL5 programs
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.
786
MQL5 programs
Runtime Errors
The executing subsystem of the client terminal has an opportunity to save the error code in case it
occurs during a MQL5 program run. There is a predefined variable _LastError for each executable
MQL5 program.
Before starting the OnInit function, the _LastError variable is reset. In case an erroneous situation
occurs during calculations or in the process of internal function calls, the _LastError variable accepts a
corresponding error code. The value stored in this variable can be obtained using the GetLastError()
function.
There are several critical errors in case of which a program is terminated immediately:
division by zero
going beyond array boundary
using an incorrect object pointer
787
MQL5 programs
To get answers to these questions, we turn to the Strategy Tester, included in the MetaTrader 5 client
terminal.
This section covers the features of program testing and optimization in the strategy tester:
Function Limitations in the Strategy Tester
Tick Generation Modes
Simulation of spread
The Global Variables of the Client Terminal
The Calculation of Indicators During Testing
Loading History during Testing
Multi-Currency Testing
Simulation of Time in the Strategy Tester
Graphical Objects in Testing
The OnTimer() Function in the Strategy Tester
The Sleep() Function in the Strategy Tester
Using the Strategy Tester for Optimization Problems in Mathematical Calculations
The Synchronization of Bars in the "Open prices only" mode
The IndicatorRelease() function in the Tester
Event Handling in the Tester
Testing Agents
The Data Exchange between the Terminal and the Agent
Using the Shared Folder of All of the Client Terminals
Using DLLs
788
MQL5 programs
trading robot's parameters. The exception is the use of these functions inside the OnInit() handler.
This allows you to easily find the cause of errors when they occur.
The
Alert(),
MessageBox(),
PlaySound(),
SendNotification(), WebRequest() Functions
SendFTP,
SendMail(),
The basic and the most detailed is the "Every tick" mode, the other two modes are the simplifications
of the basic one, and will be described in comparison to the "Every tick" mode. Consider all three
modes in order to understand the differences between them.
"Every Tick"
The historical quotes data for financial instruments is transferred from the trading server to the
MetaTrader 5 client terminal in the form of packed minute bars. Detailed information on the
occurrence of requests and the construction of the required time-frames can be obtained from the
Organizing Data Access chapter of MQL5 Reference.
The minimal element of the price history is the minute bar, from which you can obtain information on
the four values of the price:
Open - the price at which the minute bar was opened;
High - the maximum that was achieved during this minute bar;
Low - the minimum that was achieved during this minute bar;
Close - the closing price of the bar.
The new minute bar is not opened at the moment when the new minute begins (number of seconds
becomes equal to 0), but when a tick occurs - a price change by at least one point. The figure shows
the first minute bar of the new trading week, which has the opening time of 2011.01.10 00:00. The
price gap between Friday and Monday, which we see on the chart, is common, since currency rates
fluctuates even on weekends in response to incoming news.
789
MQL5 programs
For this bar, we only know that the minute bar was opened on January 10th 2011 at 00 hours 00
minutes, but we know nothing about the seconds. It could have been opened at 00:00:12 or 00:00:36
(12 or 36 seconds after the start of a new day) or any other time within that minute. But we do know
that the Open price of EURUSD was at 1.28940 at the opening time of the new minute bar.
We also don't know (accurate within a second) when we received the tick corresponding to the closing
price of the considered minute bar. We known only one thing - the last Close price of the minute bar.
For this minute, the price was 1.28958. The time of the appearance of High and Low prices is also
unknown, but we know that the maximum and minimum prices were on the levels of 1.28958 and
1.28940, respectively.
To test the trading strategy, we need a sequence of ticks, on which the work of the Expert Advisor will
be simulated. Thus, for every minute bar, we know the 4 control points, where the price has
definitely been. If a bar has only 4 ticks, then this is enough information to perform a testing, but
usually the tick volume is greater than 4.
Hence, there is a need to generate additional control points for ticks, which occurred between the
Open, High, Low, and Close prices. The principle of the "Every tick" ticks generation mode is
described in the The Algorithm of Ticks Generation within the Strategy Tester of the MetaTrader 5
Terminal a figure from which is presented below.
790
MQL5 programs
When testing in the "Every tick" mode, the OnTick() function of the EA will be called at every control
point. Each control point is a tick from a generated sequence. The EA will receive the time and price
of the simulated tick, just as it would when working online.
Important: the "Every tick" testing mode is the most accurate, but at the same time, the most
time consuming. For an initial testing of the majority of trading strategies, it is usually sufficient
to use one of the other two testing modes.
791
MQL5 programs
The figure shows a very attractive graph of this EA testing. How was it obtained? We know 4 prices for
a minute bar, and we also know that the first is the Open price, and the last is the Close price. We
have the High and Low prices between them, and the sequence of their occurrence is unknown, but it
is known, that the High price is greater than or equal to the Open price (and the Low price is less than
or equal to the Open price).
It is sufficient enough to determine the moment of receiving the Open price, and then analyze the
next tick in order to determine what price we have at the moment - either the High or the Low. If the
price is below the Open price, then we have a Low price and buy at this tick, the next tick will
correspond to the High price, at which we will close the buy and open for sell. The next tick is the last
one, this is the Close price, and we close the sale on it.
If after the price, we receive a tick with a price greater than the opening price, then the sequence of
deals is reversed. Process a minute bar in this "cheat" mode, and wait for the next one.
When testing such EA on the history, everything goes smoothly, but once we launch it online, the truth
begins to get revealed - the balance line remains steady, but heads downwards. To expose this trick,
we simply need to run the EA in the "Every tick" mode.
Note: If the test results of the EA in the rough testing modes ("1 minute OHLC" and "Open Prices
only") seem too good, make sure to test it in the "Every tick" mode.
792
MQL5 programs
The triggering of Stop Loss and Take Profit levels;
The triggering of pending orders;
The removal of expired pending orders.
If there are no open positions or pending orders, we don't need to perform these checks on hidden
ticks, and the increase of speed may be quite substantial. This "Open prices only" mode is well suited
for testing strategies, which process deals only at the opening of the bar and do not use pending
orders, as well as StopLoss and TakeProfit orders. For the class of such strategies, the necessary
accuracy of testing is preserved.
Let's use the Moving Average Expert Advisor from the standard package as an example of an EA,
which can be tested in any mode. The logic of this EA is built in such a way that all of the decisions are
made at the opening of the bar, and deals are carried out immediately, without the use of pending
orders.
Run a testing of the EA on EURUSD H1 on an interval from 2010.09.01 to 2010.12.31, and compare the
graphs. The figure shows the balance graph from the test report for all of the three modes.
As you can see, the graphs on different testing modes are exactly the same for the Moving Average EA
from the standard package.
There are some limitations on the "Open Prices Only" mode:
You cannot use the Random Delay execution mode.
In the tested Expert Advisor, you cannot access data of the timeframe lower than that used for
testing/optimization. For example, if you run testing/optimization on the H1 period, you can access
data of H2, H3, H4 etc., but not M30, M20, M10 etc. In addition, the higher timeframes that are
accessed must be multiple of the testing timeframe. For example, if you run testing in M20, you
cannot access data of M30, but it is possible to access H1. These limitations are connected with the
impossibility to obtain data of lower or non-multiple timeframes out of the bars generated during
testing/optimization.
Limitations on accessing data of other timeframes also apply to other symbols whose data are used
793
MQL5 programs
by the Expert Advisor. In this case the limitation for each symbol depends on the first timeframe
accessed during testing/optimization. Suppose, during testing on EURUSD H1, an Expert Advisor
accesses data of GBPUSD M20. In this case the Expert Advisor will be able to further use data of
EURUSD H1, H2, etc., as well as GBPUSD M20, H1, H2 etc.
Note: The "Open prices only" mode has the fastest testing time, but it is not suitable for all of the
trading strategies. Select the desired test mode based on the characteristics of the trading
system.
To conclude the section on the tick generation modes, let's consider a visual comparison of the
different tick generation modes for EURUSD, for two M15 bars on an interval from 2011.01.11
21:00:00 - 2011.01.11 21:30:00.
The ticks were saved into different files using the WriteTicksFromTester.mq5 EA and the ending of
these files names are specified in filenameEveryTick, filenameOHLC and filenameOpenPrice inputparameters.
To obtain three files with three tick sequences (for each of the following modes "Every tick", "1 minute
OHLC" and "Open prices only), the EA was launched three times in the corresponding modes, in single
runs. Then, the data from these three files were displayed on the chart using the
TicksFromTester.mq5 indicator. The indicator code is attached to this article.
794
MQL5 programs
By default, all of the file operations in the MQL5 language are made within the "file sandbox", and
during testing the EA has access only to its own "file sandbox". In order for the indicator and the EA to
work with files from one folder during testing, we used the flag FILE_COMMON. An example of code
from the EA:
//--- open the file
file=FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON,";");
//--- check file handle
if(file==INVALID_HANDLE)
{
For reading the data in the indicator, we also used the flag FILE_COMMON. This allowed us to avoid
manually transferring the necessary files from one folder to another.
//--- open the file
int file=FileOpen(fname,FILE_READ|FILE_CSV|FILE_COMMON,";");
//--- check file handle
if(file==INVALID_HANDLE)
{
PrintFormat("Error in open of file %s for reading. Error code=%d",fname,GetLastError());
return;
}
else
{
PrintFormat("File will be opened from %s",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
}
Simulation of spread
The price difference between the Bid and the Ask prices is called the spread. During testing, the
spread is not modeled but is taken from historical data. If the spread is less than or equal to zero in
the historical data, then the last known (at the moment of generation) spread is used by testing
agent.
In the Strategy Tester, the spread is always considered floating. That is, SymbolInfoInteger(symbol,
SYMBOL_SPREAD_FLOAT) always returns true.
In addition, the historical data contains tick values and trading volumes. For the storage and retrieval
of data we use a special MqlRates structure:
struct MqlRates
{
datetime time;
double
// Open price
open;
795
MQL5 programs
double
high;
double
low;
double
close;
// Close price
long
tick_volume;
// Tick volume
int
spread;
// Spread
long
real_volume;
// Trade volume
};
796
MQL5 programs
Before testing a multi-currency strategy, it is recommended to download all the necessary historical
data to the client terminal. This will help to avoid delays in testing/optimization associated with
download of the required data. You can download history, for example, by opening the appropriate
charts and scrolling them to the history beginning. An example of forced loading of history into the
terminal is available in the Organizing Access to Data section of the MQL5 Reference.
Testing agents, in turn, receive history from the terminal in the packed form. During the next testing,
the tester does not load history from the terminal, because the required data is available since the
previous run of the tester.
The terminal loads history from a trade server only once, the first time the agent requests the
history of a symbol to be tested from the terminal. The history is loaded in a packed form to
reduce the traffic.
Ticks are not sent over the network, they are generated on testing agents.
Multi-Currency Testing
The Strategy Tester allows us to perform a testing of strategies, trading on multiple symbols. Such EAs
are conventionally referred to as multi-currency Expert Advisors, since originally, in the previous
platforms, testing was performed only for a single symbol. In the Strategy Tester of the MetaTrader 5
terminal, we can model trading for all of the available symbols.
The tester loads the history of the used symbols from the client terminal (not from the trade server!)
automatically during the first call of the symbol data.
The testing agent downloads only the missing history, with a small margin to provide the necessary
data on the history, for the calculation of the indicators at the starting time of testing. For the timeframes D1 and less, the minimum volume of the downloaded history is one year.
Thus, if we run a testing on an interval 2010.11.01-2010.12.01 (testing for an interval of one month)
with a period of M15 (each bar is equal to 15 minutes), then the terminal will be requested the history
for the instrument for the entire year of 2010. For the weekly time-frame, we will request a history of
100 bars, which is about two years (a year has 52 weeks). For testing on a monthly time-frame the
agent will request the history of 8 years (12 months x 8 years = 96 months).
If there isn't necessary bars, the starting date of testing will be automatically shifted from past to
present to provide the necessary reserve of bars before the testing.
During testing, the "Market Watch" is emulated as well, from which one can obtain information on
symbols.
By default, at the beginning of testing, there is only one symbol in the "Market Watch" of the Strategy
Tester - the symbol that the testing is running on. All of the necessary symbols are connected to the
"Market Watch" of the Strategy Tester (not terminal!) automatically when referred to.
Prior to starting testing of a multi-currency Expert Advisor, it is necessary to select symbols
required for testing in the "Market Watch" of the terminal and load the required data. During the
first call of a "foreign" symbol, its history will be automatically synchronized between the testing
agent and the client terminal. A "foreign" symbol is the symbol other than that on which testing is
running.
797
MQL5 programs
Referral to the data of an "other" symbol occurs in the following cases:
When using the technical indicators function and IndicatorCreate() on the symbol/timeframe;
The request to the "Market Watch" data for the other symbol:
1. SeriesInfoInteger
2. Bars
3. SymbolSelect
4. SymbolIsSynchronized
5. SymbolInfoDouble
6. SymbolInfoInteger
7. SymbolInfoString
8. SymbolInfoTick
9. SymbolInfoSessionQuote
10.SymbolInfoSessionTrade
11.MarketBookAdd
12.MarketBookGet
Request of the time-series for a symbol/timeframe by using the following functions:
1. CopyBuffer
2. CopyRates
3. CopyTime
4. CopyOpen
5. CopyHigh
6. CopyLow
7. CopyClose
8. CopyTickVolume
9. CopyRealVolume
10.CopySpread
At the moment of the first call to an "other" symbol, the testing process is stopped and the history is
downloaded for the symbol/timeframe, from the terminal to the testing agent. At the same time, the
generation of tick sequence for this symbol is made.
An individual tick sequence is generated for each symbol, according to the selected tick generation
mode. You can also request the history explicitly for the desired symbols by calling the SymbolSelect()
in the OnInit() handler - the downloading of the history will be made immediately prior to the testing
of the Expert Advisor.
Thus, it does not require any extra effort to perform multi-currency testing in the MetaTrader 5 client
terminal. Just open the charts of the appropriate symbols in the client terminal. The history will be
automatically uploaded from the trading server for all the required symbols, provided that it contains
this data.
798
MQL5 programs
During testing, the local time TimeLocal() is always equal to the server time TimeTradeServer(). In
turn, the server time is always equal to the time corresponding to the GMT time - TimeGMT(). This
way, all of these functions display the same time during testing.
The lack of a difference between the GMT, the Local, and the server time in the Strategy Tester is
done deliberately in case there is no connection to the server. The test results should always be the
same, regardless of whether or not there is a connection. Information about the server time is not
stored locally, and is taken from the server.
timer=1;
input bool
timer_switch_on=true; // timer on
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- run the timer if
timer_switch_on==true
if(timer_switch_on)
{
EventSetTimer(timer);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
799
MQL5 programs
//--- stop the timer
EventKillTimer();
}
//+------------------------------------------------------------------+
//| Timer function
//+------------------------------------------------------------------+
void OnTimer()
{
//--// take no actions, the body of the handler is empty
}
//+------------------------------------------------------------------+
Testing time measurements were taken at different values of the timer parameter (periodicity of the
Timer event). On the obtained data, we plot a testing time as function of Timer period.
It can be clearly seen that the smaller is the parameter timer, during the initialization of the
EventSetTimer(Timer) function, the smaller is the period (Period) between the calls of the OnTimer()
handler, and the larger is the testing time T, under the same other conditions.
800
MQL5 programs
you receive this error, the test results are not rejected, all of the computations are performed in their
full volume (the number of deals, subsidence, etc.), and the results of this testing are passed on to
the terminal.
The Sleep() function will not work in OnDeinit(), since after it is called, the testing time will be
guaranteed to surpass the range of the testing interval.
for
Optimization
Problems
in
The tester in the MetaTrader 5 terminal can be used, not only to testing trading strategies, but also
for mathematical calculations. To use it, it's necessary to select the "Math calculations" mode:
In this case, only three functions will be called: OnInit(), OnTester(), OnDeinit(). In "Math calculations"
mode the Strategy Tester doesn't generate any ticks and download the history.
The Strategy Tester works in "Math calculations" mode also if you specify the starting date greater
than ending date.
When using the tester to solve mathematical problems, the uploading of the history and the
generation of ticks does not occur.
801
MQL5 programs
A typical mathematical problem for solving in the MetaTrader 5 Strategy Tester - searching for an
extremum of a function with many variables.
To solve it we need to:
The calculation of function value should be located in OnTester() function;
The function parameters must be defined as input-variables of the Expert Advisor;
Compile the EA, open the "Strategy Tester" window. In the "Input parameters" tab, select the required
input variables, and define the set of parameter values by specifying the start, stop and step values
for each of the function variables.
Select the optimization type - "Slow complete algorithm" (full search of parameters space) or "Fast
genetic based algorithm". For a simple search of the extremum of the function, it is better to choose a
fast optimization, but if you want to calculate the values for the entire set of variables, then it is best
to use the slow optimization.
Select "Math calculation" mode and using the "Start" button, run the optimization procedure. Note that
during the optimization the Strategy Tester will search for the maximum values of the OnTester
function. To find a local minimum, return the inverse of the computed function value from the
OnTester function:
return(1/function_value);
It is necessary to check that the function_value is not equal to zero, since otherwise we can obtain a
critical error of dividing by zero.
There is another way, it is more convenient and does not distort the results of optimization, it was
suggested by the readers of this article:
return(-function_value);
This option does not require the checking of the function_value for being equal to zero, and the
surface of the optimization results in a 3D-representation has the same shape. The only difference is
that it is mirrored comparing to the original.
As an example, we provide the sink() function:
The code of the EA for finding the extremum of this function is placed into the OnTester():
//+------------------------------------------------------------------+
//|
Sink.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
input double
802
MQL5 programs
//+------------------------------------------------------------------+
//| Tester function
//+------------------------------------------------------------------+
double OnTester()
{
//--double sink=MathSin(x*x+y*y);
//--return(sink);
}
//+------------------------------------------------------------------+
Perform an optimization and see the optimization results in the form of a 2D graph.
The better the value is for a given pair of parameters (x, y), the more saturated the color is. As was
expected from the view of the form of the sink() formula, its values forms concentric circles with a
center at (0,0). One can see in the 3D-graph, that the sink() function has no single global extremum:
803
MQL5 programs
The Strategy Tester generates and plays a tick sequence for each instrument in accordance with the
selected trading mode. At the same time, a new bar for each symbol is opened, regardless of how the
bar opened on another symbol. This means that when testing a multi-currency EA, a situation may
occur (and often does), when for one instrument a new bar has already opened, and for the other it
has not. Thus, in testing, everything happens just like in reality.
This authentic simulation of the history in the tester does not cause any problems as long as the
"Every tick" and "1 minute OHLC" testing modes are used. For these modes, enough ticks are
generated for one candlestick, to be able to wait until the synchronization of bars from different
symbols takes place. But how do we test multi-currency strategies in the "Open prices only" mode, if
the synchronization of bars on trading instruments is mandatory? In this mode, the EA is called only on
one tick, which corresponds to the time of the opening of the bars.
We'll illustrate it on an example: we are testing an EA on the EURUSD, and a new H1 candlestick has
been opened on EURUSD. We can easily recognize this fact - while testing in the "Open prices only"
mode, the NewTick event corresponds to the moment of a bar opening on the tested period. But there
is no guarantee that the new candlestick was opened on the USDJPY symbol, which is used in the EA.
Under normal circumstances, it is sufficient enough to complete the work of the OnTick() function and
804
MQL5 programs
to check for the emergence of a new bar on USDJPY at the next tick. But when testing in the "Open
prices only" mode, there will be no other tick, and so it may seem that this mode is not fit for testing
multi-currency EAs. But this is not so - do not forget that the tester in MetaTrader 5 behaves just as it
would in real life. You can wait until a new bar is opened on another symbols using the function
Sleep()!
The code of the EA Synchronize_Bars_Use_Sleep.mq5, which shows an example of the synchronization
of bars in the "Open prices only" mode:
//+------------------------------------------------------------------+
//|
Synchronize_Bars_Use_Sleep.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
other_symbol="USDJPY";
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- check symbol
if(_Symbol==other_symbol)
{
PrintFormat("You have to specify the other symbol in input parameters or select other symbol
//--- forced stop testing
return(INIT_PARAMETERS_INCORRECT);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
//--- static variable, used for storage of last bar time
static datetime last_bar_time=0;
//--- sync flag
static bool synchonized=false;
//--- if static variable isn't initialized
if(last_bar_time==0)
{
//--- it's first call, save bar time and exit
last_bar_time=(datetime)SeriesInfoInteger(_Symbol,Period(),SERIES_LASTBAR_DATE);
805
MQL5 programs
}
//--- get open time of the last bar of chart symbol
datetime curr_time=(datetime)SeriesInfoInteger(Symbol(),Period(),SERIES_LASTBAR_DATE);
//--- if times aren't equal
if(curr_time!=last_bar_time)
{
//--- save open bar time to the static variable
last_bar_time=curr_time;
//--- not synchronized
synchonized=false;
//--- print message
while(!(curr_time==(other_time=(datetime)SeriesInfoInteger(other_symbol,Period(),SERIES_LASTBAR_
{
PrintFormat("Waiting 5 seconds..");
//--- wait 5 seconds and call SeriesInfoInteger(other_symbol,Period(),SERIES_LASTBAR_DATE)
Sleep(5000);
}
//--- bars are synchronized
synchonized=true;
PrintFormat("Open bar time of the chart symbol %s: is %s",_Symbol,TimeToString(last_bar_time));
PrintFormat("Open bar time of the symbol %s: is %s",other_symbol,TimeToString(other_time));
//--- TimeCurrent() is not useful, use TimeTradeServer()
Print("The bars are synchronized at ",TimeToString(TimeTradeServer(),TIME_SECONDS));
}
//+------------------------------------------------------------------+
Notice the last line in the EA, which displays the current time when the fact of synchronization was
established:
Print("The bars synchronized at ",TimeToString(TimeTradeServer(),TIME_SECONDS));
To display the current time we used the TimeTradeServer() function rather than TimeCurrent(). The
TimeCurrent() function returns the time of the last tick, which does not change after using Sleep().
Run the EA in the "Open prices only" mode, and you will see a message about the synchronization of
the bars.
Use the TimeTradeServer() function instead of the TimeCurrent(), if you need to obtain the current
server time, and not the time of the last tick arrival.
806
MQL5 programs
There is another way to synchronize bars - using a timer. An example of such an EA is
Synchronize_Bars_Use_OnTimer.mq5, which is attached to this article.
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--bool hidden=IndicatorRelease(handle_ind);
if(hidden) Print("IndicatorRelease() successfully completed");
else Print("IndicatorRelease() returned false. Error code ",GetLastError());
}
In order to prohibit the showing of the indicator on the chart, after the completion of a single test, use
the function IndicatorRelease() in the handler OnDeinit().
807
MQL5 programs
OnTick() - Event handler of a new tick arrival;
OnTrade() - Trading event handler;
OnTimer() - Event handler of a signal arrival from the timer;
OnChartEvent() - a handler for client events.
When testing in an EA, we can handle custom events using the OnChartEvent() function, but in the
indicators, this function can not be called in the tester. Even if the indicator has the OnChartEvent()
event handler and this indicator is used in the tested EA, the indicator itself will not receive any
custom events.
During testing, an Indicator can generate custom events using the EventChartCustom() function, and
the EA can process this event in the OnChartEvent().
In addition to these events, special events associated with the process of testing and optimization are
generated in the strategy tester:
Tester - this event is generated after completion of Expert Advisor testing on history data. The
Tester event is handled using the OnTester() function. This function can be used only when testing
Expert Advisor and is intended primarily for the calculation of a value that is used as a Custom max
criterion for genetic optimization of input parameters.
TesterInit - this event is generated during the start of optimization in the strategy tester before the
very first pass. The TesterInit event is handled using the OnTesterInit() function. During the start of
optimization, an Expert Advisor with this handler is automatically loaded on a separate terminal
chart with the symbol and period specified in the tester, and receives the TesterInit event. The
function is used to initiate an Expert Advisor before start of optimization for further processing of
optimization results.
TesterPass - this event is generated when a new data frame is received. The TesterPass event is
handled using the OnTesterPass() function. An Expert Advisor with this handler is automatically
loaded on a separate terminal chart with the symbol/period specified for testing, and receives the
TesterPass event when a frame is received during optimization. The function is used for dynamic
handling of optimization results "on the spot" without waiting for its completion. Frames are added
using the FrameAdd() function, which can be called after the end of a single pass in the OnTester()
handler.
TesterDeinit - this event is generated after the end of Expert Advisor optimization in the strategy
tester. The TesterDeinit event is handles using the OnTesterDeinit() function. An Expert Advisor
with this handler is automatically loaded on a chart at the start of optimization, and receives
TesterDeinit after its completion. The function is used for final processing of all optimization
results.
Testing Agents
Testing in the MetaTrader 5 client terminal is carried out using test agents. Local agents are created
and enabled automatically. The default number of local agents corresponds to the number of cores in a
computer.
Each testing agent has its own copy of the global variables, which is not related to the client terminal.
The terminal itself is the dispatcher, which distributes the tasks to the local and remote agents. After
executing a task on the testing of an EA, with the given parameters, the agent returns the results to
the terminal. With a single test, only one agent is used.
The agent stores the history, received from the terminal, in separate folders, by the name of the
808
MQL5 programs
instrument, so the history for EURUSD is stored in a folder named EURUSD. In addition, the history of
the instruments is separated by their sources. The structure for storing the history looks the following
way:
tester_catalog\Agent-IPaddress-Port\bases\name_source\history\symbol_name
For example, the history for EURUSD from the server MetaQuotes-Demo can be stored in the folder
tester_catalog\Agent-127.0.0.1-3000\bases\MetaQuotes-Demo\EURUSD.
A local agent, after the completion of testing, goes into a standby mode, awaiting for the next task
for another 5 minutes, so as not to waste time on launching for the next call. Only after the waiting
period is over, the local agent shuts down and unloads from the CPU memory.
In case of an early completion of the testing, from the user's side (the "Cancel" button), as well as with
the closing of the client terminal, all local agents immediately stop their work and are unloaded from
the memory.
criterion, etc.)
The list of the selected symbols in the "Market Watch"
The specification of the testing symbol (the contract size, the allowable margins from the market
tester_indicator
string
tester_file
string
809
MQL5 programs
string
Library
name
with
the
extension, in double quotes. A
library can have extension dll
or ex5. Libraries that require
testing
are
defined
automatically. However, if any
of libraries is used by a
custom indicator, this property
is required
For each block of parameters, a digital fingerprint in the form of MD5-hash is created, which is sent to
the agent. MD5-hash is unique for each set, its volume is many more times smaller than the amount of
information on which it is calculated.
The agent receives a hash of blocks and compares them with those that it already has. If the
fingerprint of the given parameter block is not present in the agent, or the received hash is different
from the existing one, the agent requests this block of parameters. This reduces the traffic between
the terminal and the agent.
After the testing, the agent returns to the terminal all of the results of the run, which are shown in the
tabs "Test Results" and "Optimization Results": the received profit, the number of deals, the Sharpe
coefficient, the result of the OnTester() function, etc.
During optimizing, the terminal hands out testing tasks to the agents in small packages, each package
contains several tasks (each task means single testing with a set of input parameters). This reduces
the exchange time between the terminal and the agent.
The agents never record to the hard disk the EX5-files, obtained from the terminal (EA, indicators,
libraries, etc.) for security reasons, so that a computer with a running agent could not use the sent
data. All other files, including DLL, are recorded in the sandbox. In remote agents you can not test EAs
using DLL.
The testing results are added up by the terminal into a special cache of results (the result cache), for a
quick access to them when they are needed. For each set of parameters, the terminal searches the
result cache for already available results from the previous runs, in order to avoid re-runs. If the result
with such a set of parameters is not found, the agent is given the task to conduct the testing.
All traffic between the terminal and the agent is encrypted.
Ticks are not sent over the network, they are generated on testing agents.
810
MQL5 programs
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- the shared folder for all of the client terminals
common_folder=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
//--- draw out the name of this folder
PrintFormat("Open the file in the shared folder of the client terminals %s", common_folder);
//--- open a file in the shared folder (indicated by FILE_COMMON flag)
handle=FileOpen(filename,FILE_WRITE|FILE_READ|FILE_COMMON);
... further actions
//--return(INIT_SUCCEEDED);
}
Using DLLs
To speed up the optimization we can use not only local, but also remote agents. In this case, there are
some limitations for remote agents. First of all, remote agents do not display in their logs the results
of the execution of the Print() function, messages about the opening and closing of positions. A
minimum of information is displayed in the log to prevent incorrectly written EAs from trashing up the
computer, on which the remote agent is working, with messages.
A second limitation - the prohibition on the use of DLL when testing EAs. DLL calls are absolutely
forbidden on remote agents for security reasons. On local agent, DLL calls in tested EAs are allowed
only with the appropriate permission "Allow import DLL".
811
MQL5 programs
Note: When using 3rd party EAs (scripts, indicators) that require allowed DLL calls, you should be
aware of the risks which you assume when allowing this option in the settings of the terminal.
Regardless of how the EA will be used - for testing or for running on a chart.
812
Predefined Variables
Value
_Digits
_Point
_LastError
_Period
_RandomSeed
_StopFlag
_Symbol
_UninitReason
Predefined variables cannot be defined in a library. A library uses such variables that are defined in
program from which this library is called.
813
Predefined Variables
int _Digits
The _Digits variable stores number of digits after a decimal point, which defines the price accuracy of
the symbol of the current chart.
You may also use the Digits() function.
814
Predefined Variables
double _Point
The _Point variable contains the point size of the current symbol in the quote currency.
You may also use the Point() function.
815
Predefined Variables
int _LastError
The _LastError variable contains code of the last error, that occurred during the mql5-program run. Its
value can be reset to zero by ResetLastError().
To obtain the code of the last error, you may also use the GetLastError() function.
816
Predefined Variables
int _Period
The _Period variable contains the value of the timeframe of the current chart.
Also you may use the Period() function.
See also
PeriodSeconds, Chart timeframes, Date and Time, Visibility of objects
817
Predefined Variables
_RandomSeed
Variable for storing the current state when generating pseudo-random integers. _RandomSeed changes
its value when calling MathRand(). Use MathSrand() to set the required initial condition.
x random number received by MathRand() function is calculated in the following way at each call:
x=_RandomSeed*214013+2531011;
_RandomSeed=x;
x=(x>>16)&0x7FFF;
See also
MathRand(), MathSrand(), Integer types
818
Predefined Variables
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.
819
Predefined Variables
string _Symbol
The _Symbol variable contains the symbol name of the current chart.
You may also use the Symbol() function.
820
Predefined Variables
int _UninitReason
The _UninitReason variable contains the code of the program uninitialization reason.
Usually, this code is obtained by UninitializeReason()the function.
821
Common Functions
Common Functions
General-purpose functions not included into any specialized group are listed here.
Function
Action
Alert
CheckPointer
Comment
CryptEncode
CryptDecode
DebugBreak
ExpertRemove
GetPointer
GetTickCount
GetMicrosecondCount
MessageBox
PeriodSeconds
PlaySound
PrintFormat
ResetLastError
ResourceCreate
ResourceFree
ResourceReadImage
ResourceSave
SendFTP
822
Common Functions
SendNotification
Sleep
TerminalClose
TesterStatistics
WebRequest
ZeroMemory
823
Common Functions
Alert
Displays a message in a separate window.
void Alert(
argument,
// first value
...
// other values
);
Parameters
argument
[in] Any values separated by commas. To split the information output in several lines you can use
the line feed character "\n" or "\r\n". The number of parameters can not exceed 64.
Return Value
No return value.
Note
Arrays can't be passed to the Alert() function. Arrays should be output elementwise. Data of the
double type are output with 8 digits after the decimal point, data of the float type are displayed with
5 digits after the decimal point. To output the real numbers with a different precision or in a
scientific format, use the DoubleToString() function.
Data of the bool type is output as "true" or "false" strings. Dates are output as YYYY.MM.DD
HH:MI:SS. To display a date in another format use the TimeToString() function. Data of the color
type are output either as an R,G,B string or as a color name, if the color is present in a color set.
Alert() function does not work in the Strategy Tester.
824
Common Functions
CheckPointer
The function returns the type of the object pointer.
ENUM_POINTER_TYPE CheckPointer(
object* anyobject
// object pointer
);
Parameters
anyobject
[in] Object pointer.
Return value
Returns a value from the ENUM_POINTER_TYPE enumeration.
Note
An attempt to call an incorrect pointer results in the critical termination of a program. That's why
it's necessary to call the CheckPointer function before using a pointer. A pointer can be incorrect in
the following cases:
the pointer is equal to NULL;
the object has been deleted using the delete operator.
This function can be used for checking pointer validity. A non-zero value warranties that the pointer
can be used for accessing.
Example:
//+------------------------------------------------------------------+
//| Deletes list by deleting its elements
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer for working in the loop
CItem* item;
//--- go through loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamic object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//--}
825
Common Functions
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
826
Common Functions
Comment
This function outputs a comment defined by a user in the top left corner of a chart.
void Comment(
argument,
// first value
...
// next values
);
Parameters
...
[in] 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
Arrays can't be passed to the Comment() function. Arrays must be entered element-by-element.
Data of double type are output with the accuracy of up to 16 digits after a decimal point, and can be
output either in traditional or in scientific format, depending on what notation will be more
compact. Data of float type are output with 5 digits after a decimal point. To output real numbers
with another accuracy or in a predefined format, use the DoubleToString() function.
Data of bool type are output as "true" or "false" strings. Dates are shown as YYYY.MM.DD HH:MI:SS.
To show dates in another format, use the TimeToString() function. Data of color type are output
either as R,G,B string or as a color name, if this color is present in the color set.
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
827
Common Functions
CryptEncode
Transforms the data from array with the specified method.
int CryptEncode(
ENUM_CRYPT_METHOD
method,
// method
const uchar&
data[],
// source array
const uchar&
key[],
// key
uchar&
result[]
// destination array
);
Parameters
method
[in]
Data transformation method. Can be one of the values of ENUM_CRYPT_METHOD
enumeration.
data[]
[in] Source array.
key[]
[in] Key array.
result[]
[out] Destination array.
Return Value
Amount of bytes in the destination array or 0 in case of error. To obtain information about the error
call the GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| ArrayToHex
//+------------------------------------------------------------------+
string ArrayToHex(uchar &arr[],int count=-1)
{
string res="";
//--- check
if(count<0 || count>ArraySize(arr))
count=ArraySize(arr);
//--- transform to HEX string
for(int i=0; i<count; i++)
res+=StringFormat("%.2X",arr[i]);
//--return(res);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
828
Common Functions
{
string text="The quick brown fox jumps over the lazy dog";
string keystr="ABCDEFG";
uchar src[],dst[],key[];
//--- prepare key
StringToCharArray(keystr,key);
//--- copy text to source array src[]
StringToCharArray(text,src);
//--- print initial data
PrintFormat("Initial data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
//--- encrypt src[] with DES 56-bit key in key[]
int res=CryptEncode(CRYPT_DES,src,key,dst);
//--- check error
if(res>0)
{
//--- print encrypted data
PrintFormat("Encoded data: size=%d %s",res,ArrayToHex(dst));
//--- decode dst[] to src[]
res=CryptDecode(CRYPT_DES,dst,key,src);
//--- check error
if(res>0)
{
//--- print decoded data
PrintFormat("Decoded data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
}
else
Print("Error in CryptDecode. Error code=",GetLastError());
}
else
Print("Error in CryptEncode. Error code=",GetLastError());
}
See also
Array Functions, CryptDecode()
829
Common Functions
CryptDecode
Performs the inverse transformation of the data from array, tranformed by CryptEncode().
int CryptEncode(
ENUM_CRYPT_METHOD
method,
// method
const uchar&
data[],
// source array
const uchar&
key[],
// key
uchar&
result[]
// destination array
);
Parameters
method
[in]
Data transformation method. Can be one of the values of ENUM_CRYPT_METHOD
enumeration.
data[]
[in] Source array.
key[]
[in] Key array.
result[]
[out] Destination array.
Return Value
Amount of bytes in the destination array or 0 in case of error. To obtain information about the error
call the GetLastError() function.
See also
Array Functions, CryptEncode()
830
Common Functions
DebugBreak
It is a program breakpoint in debugging.
void DebugBreak();
Return Value
No return value.
Note
Execution of an MQL5 program is interrupted only if a program is started in a debugging mode. The
function can be used for viewing values of variables and/or for further step-by-step execution.
831
Common Functions
ExpertRemove
The function stops an Expert Advisor and unloads it from a chart.
void ExpertRemove();
Return Value
No return value.
Note
The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag to stop the
EA operation is set. That is, any next event won't be processed, OnDeinit() will be called and the
Expert Advisor will be unloaded and removed from the chart.
Example:
//+------------------------------------------------------------------+
//|
Test_ExpertRemove.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//+------------------------------------------------------------------+
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)
{
832
Common Functions
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}
Print("tick_counter =",tick_counter);
//--}
//+------------------------------------------------------------------+
See also
Program running, Client terminal events
833
Common Functions
GetPointer
The function returns the object pointer.
void* GetPointer(
any_class anyobject
);
Parameters
anyobject
[in] Object of any class.
Return Value
The function returns the object pointer.
Note
Only class objects have pointers. Instances of structures and simple-type variables can't have
pointers. The class object not created using the new() operator, but, e.g., automatically created in
the array of objects, still has a pointer. But this pointer will be of the automatic type
POINTER_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 an error.
An attempt to call an incorrect pointer causes the critical termination of a program. That's why the
CheckPointer() function should be called prior to using a pointer. A pointer can be incorrect in the
following cases:
the pointer is equal to NULL;
the object has been deleted using the delete operator.
This function can be used to check the validity of a pointer. A non-zero value guarantees, that the
pointer can be used for accessing.
Example:
//+------------------------------------------------------------------+
//|
Check_GetPointer.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//+------------------------------------------------------------------+
//| Class implementing the list element
//+------------------------------------------------------------------+
834
Common Functions
class CItem
{
int
m_id;
string
m_comment;
CItem*
m_next;
public:
CItem() { m_id=0; m_comment=NULL; m_next=NULL; }
~CItem() { Print("Destructor of ",m_id,
(CheckPointer(GetPointer(this))==POINTER_DYNAMIC)?
"dynamic":"non-dynamic"); }
void
void
PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }
int
Identifier() { return(m_id); }
CItem*
Next() {return(m_next); }
void
};
//+------------------------------------------------------------------+
//| Simplest class of the list
//+------------------------------------------------------------------+
class CMyList
{
CItem*
m_items;
public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool
InsertToBegin(CItem* item);
void
Destroy();
};
//+------------------------------------------------------------------+
//| Inserts list element at the beginning
//+------------------------------------------------------------------+
bool CMyList::InsertToBegin(CItem* item)
{
if(CheckPointer(item)==POINTER_INVALID) return(false);
//--item.Next(m_items);
m_items=item;
//--return(true);
}
//+------------------------------------------------------------------+
//| Deleting the list by deleting elements
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer to work in a loop
CItem* item;
//--- go through the loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
835
Common Functions
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//--}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
CMyList list;
CItem
items[10];
CItem*
item;
//--- create and add into the list a dynamic object pointer
item=new CItem;
if(item!=NULL)
{
item.Initialize(100,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- add automatic pointers into the list
for(int i=0; i<10; i++)
{
items[i].Initialize(i,"automatic");
items[i].PrintMe();
item=GetPointer(items[i]);
if(CheckPointer(item)!=POINTER_INVALID)
list.InsertToBegin(item);
}
//--- add one more dynamic object pointer at the list beginning
item=new CItem;
if(item!=NULL)
{
item.Initialize(200,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- delete all the list elements
list.Destroy();
//--- all the list elements will be deleted after the script is over
//--- see the Experts tab in the terminal
836
Common Functions
}
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
837
Common Functions
GetTickCount
The GetTickCount() function returns the number of milliseconds that elapsed since the system start.
uint GetTickCount();
Return Value
Value of uint type.
Note
Counter is limited by the restrictions of the system timer. Time is stored as an unsigned integer, so
it's overfilled every 49.7 days if a computer works uninterruptedly.
Example:
#define MAX_SIZE 40
//+------------------------------------------------------------------+
//| Script for measuring computation time of 40 Fibonacci numbers
//+------------------------------------------------------------------+
void OnStart()
{
//--- Remember the initial value
uint start=GetTickCount();
//--- A variable for getting the next number in the Fibonacci series
long fib=0;
//--- In loop calculate the specified amount of numbers from Fibonacci series
for(int i=0;i<MAX_SIZE;i++) fib=TestFibo(i);
//--- Get the spent time in milliseconds
uint time=GetTickCount()-start;
//--- Output a message to the Experts journal
PrintFormat("Calculating %d first Fibonacci numbers took %d ms",MAX_SIZE,time);
//--- Script completed
return;
}
//+------------------------------------------------------------------+
//| Function for getting Fibonacci number by its serial number
//+------------------------------------------------------------------+
long TestFibo(long n)
{
//--- The first member of the Fibonacci series
if(n<2) return(1);
//--- All other members are calculated by the following formula
return(TestFibo(n-2)+TestFibo(n-1));
}
See also
Date and Time
838
Common Functions
GetMicrosecondCount
The GetMicrosecondCount() function returns the number of microseconds that have elapsed since the
start of MQL5-program.
ulong GetMicrosecondCount();
Return Value
Value of ulong type.
Example:
//+------------------------------------------------------------------+
//| Test function
//+------------------------------------------------------------------+
void Test()
{
int
res_int=0;
double res_double=0;
//--for(int i=0;i<10000;i++)
{
res_int+=i*i;
res_int++;
res_double+=i*i;
res_double++;
}
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
uint
ui=0,ui_max=0,ui_min=INT_MAX;
ulong
ul=0,ul_max=0,ul_min=INT_MAX;
ui_res=0;
ulong ul_res=0;
//--for(int n=0;n<2;n++)
{
//--- select measurement type
if(n==0) ui=GetTickCount();
else
ul=GetMicrosecondCount();
839
Common Functions
if(n==0) ui_res+=GetTickCount()-ui;
else
ul_res+=GetMicrosecondCount()-ul;
}
//--- calculate minimum and maximum time for both measurements
if(ui_min>ui_res) ui_min=ui_res;
if(ui_max<ui_res) ui_max=ui_res;
if(ul_min>ul_res) ul_min=ul_res;
if(ul_max<ul_res) ul_max=ul_res;
}
//--Print("GetTickCount error(msec): ",ui_max-ui_min);
Print("GetMicrosecondCount error(msec): ",DoubleToString((ul_max-ul_min)/1000.0,2));
}
See also
Date and Time
840
Common Functions
MessageBox
It creates and shows a message box and manages it. A message box contains a message and header,
any combination of predefined signs and command buttons.
int MessageBox(
string text,
// message text
string caption=NULL,
// box header
int
flags=0
);
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 it down.
MessageBox() function does not work in the Strategy Tester.
841
Common Functions
PeriodSeconds
This function returns number of seconds in a period.
int PeriodSeconds(
ENUM_TIMEFRAMES period=PERIOD_CURRENT
// chart period
);
Parameters
period=PERIOD_CURRENT
[in] Value of a chart period from the enumeration ENUM_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
Number of seconds in a selected period.
See also
_Period, Chart timeframes, Date and Time, Visibility of objects
842
Common Functions
PlaySound
It plays a sound file.
bool PlaySound(
string filename
// file name
);
Parameters
filename
[in] Path to a sound file. If filename=NULL, the playback is stopped.
Return Value
true if the file is found, otherwise - false.
Note
The file must be located in terminal_directory\Sounds or its sub-directory. Only WAV files are
played.
Call of PlaySound() with NULL parameter stops playback.
PlaySound() function does not work in the Strategy Tester.
See also
Resources
843
Common Functions
Print
It enters a message in the Expert Advisor log. Parameters can be of any type.
void Print(
argument,
// first value
...
// next values
);
Parameters
...
[in] Any values separated by commas. The number of parameters cannot exceed 64.
Note
Arrays cannot be passed to the Print() function. Arrays must be input element-by-element.
Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be
output either in traditional or in scientific format, depending on what entry will be more compact.
Data of float type are output with 5 digits after a decimal point. To output real numbers with
another accuracy or in a predefined format, use the PrintFormat() function.
Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS. To
show data in another format, use 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.
Print() function does not work during optimization in the Strategy Tester.
Example:
void OnStart()
{
//--- Output DBL_MAX using Print(), this is equivalent to PrintFormat(%%.16G,DBL_MAX)
Print("---- how DBL_MAX looks like -----");
Print("Print(DBL_MAX)=",DBL_MAX);
//--- Now output a DBL_MAX number using PrintFormat()
PrintFormat("PrintFormat(%%.16G,DBL_MAX)=%.16G",DBL_MAX);
//--- Output to the Experts journal
// Print(DBL_MAX)=1.797693134862316e+308
// PrintFormat(%.16G,DBL_MAX)=1.797693134862316E+308
//--- See how float is output
float c=(float)M_PI; // We should explicitly cast to the target type
Print("c=",c, "
// c=3.14159
Pi=",M_PI, "
Pi=3.141592653589793
(float)M_PI=",(float)M_PI);
(float)M_PI=3.14159
//--- Show what can happen with arithmetic operations with real types
double a=7,b=200;
Print("---- Before arithmetic operations");
Print("a=",a,"
b=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Divide a by b (7/200)
844
Common Functions
a=a/b;
//--- Now emulate restoring a value in the b variable
b=7.0/a; // It is expected that b=7.0/(7.0/200.0)=>7.0/7.0*200.0=200 - but it differs
//--- Output the newly calculated value of b
Print("----- After arithmetic operations");
Print("Print(b)=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Output to the Experts journal
// Print(b)=200.0
// Print(DoubleToString(b,16))=199.9999999999999716 (see that b is no more equal to 200.0)
//--- Create a very small value epsilon=1E-013
double epsilon=1e-13;
Print("---- Create a very small value");
Print("epsilon=",epsilon); // Get epsilon=1E-013
//--- Now subtract epsilon from b and again output the value to the Experts journal
b=b-epsilon;
//--- Use two ways
Print("---- After subtracting epsilon from the b variable");
Print("Print(b)=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Output to the Experts journal
// Print(b)=199.9999999999999
// Print(DoubleToString(b,16))=199.9999999999998578
//
See also
DoubleToString, StringFormat
845
Common Functions
PrintFormat
It formats and enters sets of symbols and values in the Expert Advisor log in accordance with a preset
format.
void PrintFormat(
string format_string,
// format string
...
);
Parameters
format_string
[in] A format string consists of simple symbols, and if the format string is followed by arguments,
it also contains format specifications.
...
[in] Any values of simple types separated by commas. Total number of parameters can't exceed 64
including the format string.
Return Value
String.
Note
PrintFormat() function does not work during optimization in the Strategy Tester.
The number, order and type of parameters must exactly match the set of qualifiers, otherwise the
print result is undefined. Instead of PrintFormat() you can use printf().
If the format string is followed by parameters, this string must contain format specifications that
denote output format of these parameters. Specification of format always starts with the percent
sign (%).
A format string 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 string is transformed and output according to
the preset specification. The second format specification calls transformation and output of the
second parameter, and so on till the format string end.
The format specification has the following form:
%[flags][width][.precision][{h | l | ll | I32 | I64}]type
Each field of the format specification is either a simple symbol, or a number denoting a simple
format option. The simplest format specification contains only the percent sign (%) and a symbol
defining the type of the output parameter (for example, %s). If you need to output the percent sign
in the format string, use the format specification %%.
flags
Flag
Description
Default Behavior
846
Common Functions
(minus)
Right justification
+ (plus)
0 (zero)
Nothing is added
space
Nothing is added
width
A non-negative decimal number that sets the minimal number of output symbols of the formatted
value. If the number of output symbols is less than the specified width, the corresponding number of
spaces is added from the left or right depending on the alignment (flag ). If there is flag zero (0),
the corresponding number of zeroes is added before the output value. If the number of output
symbols is greater than the specified width, the output value is never cut off.
If an 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
2000-2016, MetaQuotes Software Corp.
847
Common Functions
A non-negative decimal number that sets the output accuracy - number of digits after a decimal
point. As distinct from width specification, accuracy specification can cut off the part of fractional
type with or without rounding.
The use of accuracy specification is different for different format types.
Types
Description
Default Behavior
a, A
c, C
Not used
d, i, u, o, x, X
e, E, f
g, G
s, S
Sets number of
output
symbols of a string. If the
string length exceeds the
accuracy, the string is cut off.
of
Default accuracy 6.
Default accuracy 1.
h | l | ll | I32 | I64
Specification of data sizes, passed as a parameter.
Parameter Type
Used Prefix
int
l (lower case L)
d, i, o, x, or X
uint
l (lower case L)
o, u, x, or X
long
d, i, o, x, or X
short
d, i, o, x, or X
ushort
o, u, x, or X
int
I32
d, i, o, x, or X
are
848
Common Functions
uint
I32
o, u, x, or X
long
I64
d, i, o, x, or X
ulong
I64
o, u, x, or X
type
Type specifier is the only obligatory field for formatted output.
Symbol
Type
Output Format
int
Symbol
of
(Unicode)
int
int
int
int
int
int
Unsigned
hexadecimal
integer, using "abcdef"
int
Unsigned
hexadecimal
integer, using "ABCDEF"
double
double
double
short
type
849
Common Functions
double
double
double
double
string
String output
850
Common Functions
void OnStart()
{
//--- trade server name
string server=AccountInfoString(ACCOUNT_SERVER);
//--- account number
int login=(int)AccountInfoInteger(ACCOUNT_LOGIN);
//--- long value output
long leverage=AccountInfoInteger(ACCOUNT_LEVERAGE);
PrintFormat("%s %d: leverage = 1:%I64d",
server,login,leverage);
//--- account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
//--- double value output with 2 digits after the decimal point
double equity=AccountInfoDouble(ACCOUNT_EQUITY);
PrintFormat("%s %d: account equity = %.2f %s",
server,login,equity,currency);
//--- double value output with mandatory output of the +/- sign
double profit=AccountInfoDouble(ACCOUNT_PROFIT);
PrintFormat("%s %d: current result for open positions = %+.2f %s",
server,login,profit,currency);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
string format_string=StringFormat("%%s: point value = %%.%df",_Digits);
PrintFormat(format_string,_Symbol,point_value);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
PrintFormat("%s: current spread in points = %d ",
_Symbol,spread);
//--- double value output in the scientific (floating point) format with 17 meaningful digits after
PrintFormat("DBL_MAX = %.17e",DBL_MAX);
//--- double value output in the scientific (floating point) format with 17 meaningful digits after
PrintFormat("EMPTY_VALUE = %.17e",EMPTY_VALUE);
//--- output using PrintFormat() with default accuracy
PrintFormat("PrintFormat(EMPTY_VALUE) = %e",EMPTY_VALUE);
//--- simple output using Print()
Print("Print(EMPTY_VALUE) = ",EMPTY_VALUE);
/* execution result
MetaQuotes-Demo 1889998: leverage = 1:100
MetaQuotes-Demo 1889998: account equity = 22139.86 USD
MetaQuotes-Demo 1889998: current result for open positions = +174.00 USD
EURUSD: point value = 0.00001
EURUSD: current spread in points = 12
DBL_MAX = 1.79769313486231570e+308
EMPTY_VALUE = 1.79769313486231570e+308
PrintFormat(EMPTY_VALUE) = 1.797693e+308
Print(EMPTY_VALUE) = 1.797693134862316e+308
*/
}
See also
StringFormat, DoubleToString, Real types(double,float)
851
Common Functions
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 the _LastError variable. Usually the
ResetLastError() function is called before calling a function, after which an error appearance is
checked.
852
Common Functions
ResourceCreate
Creates an image resource based on a data set. There are two variants of the function:
Creating a resource based on a file
bool ResourceCreate(
const string
resource_name,
// Resource name
const string
path
);
resource_name,
// Resource name
const uint&
data[],
uint
img_width,
uint
img_height,
uint
data_xoffset,
uint
data_yoffset,
uint
data_width,
ENUM_COLOR_FORMAT color_format
);
Parameters
resource_name
[in] Resource name.
data[][]
[in] A one-dimensional or two-dimensional array for creating a complete image.
img_width
[in] The width of the rectangular image area in pixels to be placed in the resource in the form of
an image. It cannot be greater than the data_width value.
img_height
[in] The height of the rectangular image area in pixels to be placed in the resource in the form of
an image.
data_xoffset
[in] The horizontal rightward offset of the rectangular area of the image.
data_yoffset
[in] The vertical downward offset of the rectangular area of the image.
data_width
[in] Required only for one-dimensional arrays. It denotes the full width of the image from the data
set. If data_width=0, it is assumed to be equal to img_width. For two-dimensional arrays the
parameter is ignored and is assumed to be equal to the second dimension of the data[] array.
color_format
[in] Color processing method, from a value from the ENUM_COLOR_FORMAT enumeration.
853
Common Functions
Return Value
Returns true if successful, otherwise false. To get information about the error call the
GetLastError() function. The following errors may occur:
4015 ERR_RESOURCE_NAME_DUPLICATED (identical names of the dynamic and the static
resource)
4016 ERR_RESOURCE_NOT_FOUND (the resource is not found)
4017 ERR_RESOURCE_UNSUPPORTED_TYPE (this type of resource is not supported)
4018 ERR_RESOURCE_NAME_IS_TOO_LONG (the name of the resource is too long)
Note
If the second version of the function is called for creating the same resource with different width,
height and shift parameters, it does not create a new resource, but simply updates the existing one.
The first version of the function is used for uploading images and sounds from files, and the second
version is used only for the dynamic creation of images.
Images must be in the BMP format with a color depth of 24 or 32 bits. Sounds can only be in the
WAV format. The size of the resource should not exceed 16 Mb.
ENUM_COLOR_FORMAT
Identifier
Description
COLOR_FORMAT_XRGB_NOALPHA
COLOR_FORMAT_ARGB_RAW
COLOR_FORMAT_ARGB_NORMALIZE
See also
Resources, ObjectCreate(), ObjectSetString(), OBJPROP_BMPFILE
854
Common Functions
ResourceFree
The function deletes dynamically created resource (freeing the memory allocated for it).
bool ResourceFree(
const string resource_name
// resource name
);
Parameters
resource_name
[in] Resource name should start with "::".
Return Value
True if successful, otherwise false. To get information about the error, call the GetLastError()
function.
Note
ResourceFree() allows mql5 application developers to manage memory consumption when actively
working with resources. Graphical objects bound to the resource being deleted from the memory will
be displayed correctly after its deletion. However, newly created graphical objects (OBJ_BITMAP and
OBJ_BITMAP_LABEL) will not be able to use the deleted resource.
The function deletes only dynamic resources created by the program.
See also
Resources, ObjectCreate(), PlaySound(), ObjectSetString(), OBJPROP_BMPFILE
855
Common Functions
ResourceReadImage
The function reads data from the graphical resource created by ResourceCreate() function or saved in
EX5 file during compilation.
bool ResourceReadImage(
const string
resource_name,
uint&
data[],
uint&
width,
uint&
height,
);
Parameters
resource_name
[in] Name of the graphical resource containing an image. To gain access to its own resources, the
name is used in brief form "::resourcename". If we download a resource from a compiled EX5 file,
the full name should be used with the path relative to MQL5 directory, file and resource names
"path\\filename.ex5::resourcename".
data[][]
[in] One- or two-dimensional array for receiving data from the graphical resource.
img_width
[out] Graphical resource image width in pixels.
img_height
[out] Graphical resource image height in pixels.
Return Value
true if successful, otherwise false. To get information about the error, call the GetLastError()
function.
Note
If
data[]
array
is
then
to
be
used
for
creating
a
graphical resource,
COLOR_FORMAT_ARGB_NORMALIZE or COLOR_FORMAT_XRGB_NOALPHA color formats should be
used.
If data[] array is two-dimensional and its second dimension is less than X(width) graphical resource
size, ResourceReadImage() function returns false and reading is not performed. But if the resource
exists, actual image size is returned to width and height parameters. This will allow making another
attempt to receive data from the resource.
See also
Resource, ObjectCreate(), ObjectSetString(), OBJPROP_BMPFILE
856
Common Functions
ResourceSave
Saves a resource into the specified file.
bool ResourceSave(
const string resource_name
// Resource name
// File name
);
Parameters
resource_name
[in] The name of the resource, must start with "::".
file_name
[in] The name of the file relative to MQL5\Files.
Return Value
true in case of success, otherwise false. For the error information call GetLastError().
Note
The function always overwrites a file and creates all the required intermediate directories in the file
name if necessary.
See also
Resources, ObjectCreate(), PlaySound(), ObjectSetString(), OBJPROP_BMPFILE
857
Common Functions
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
*/
}
858
Common Functions
SendFTP
Sends a file at the address, specified in the setting window of the "FTP" tab.
bool SendFTP(
string filename,
string ftp_path=NULL
// ftp catalog
);
Parameters
filename
[in] Name of sent file.
ftp_path=NULL
[in] FTP catalog. If a directory is not specified, directory described in settings is used.
Return Value
In case of failure returns 'false'.
Note
Sent file must be located in the folder terminal_directory\MQL5\files or its subfolders. Sending isn't
performed if FTP address and/or access password are not specified in settings.
SendFTP() function does not work in the Strategy Tester.
859
Common Functions
SendNotification
Sends push notifications to the mobile terminals, whose MetaQuotes IDs are specified in the
"Notifications" tab.
bool SendNotification(
string text
);
Parameters
text
[in] The text of the notification. The message length should not exceed 255 characters.
Return Value
true if a notification has been successfully sent from the terminal; in case of failure returns false.
When checking after a failed push of notification, GetLastError () may return one of the following
errors:
4515 ERR_NOTIFICATION_SEND_FAILED,
4516 ERR_NOTIFICATION_WRONG_PARAMETER,
4517 ERR_NOTIFICATION_WRONG_SETTINGS,
4518 ERR_NOTIFICATION_TOO_FREQUENT.
Note
Strict use restrictions are set for the SendNotification() function: no more than 2 calls per second
and not more than 10 calls per minute. Monitoring the frequency of use is dynamic. The function can
be disabled in case of the restriction violation.
SendNotification() function does not work in the Strategy Tester.
860
Common Functions
SendMail
Sends an email at the address specified in the settings window of the "Email" tab.
bool SendMail(
string subject,
// header
string some_text
// email text
);
Parameters
subject
[in] Email header.
some_text
[in] Email body.
Return Value
true if an email is put into the send queue, otherwise - false.
Note
Sending can be prohibited in settings, email address can be omitted as well. For the error
information call GetLastError().
SendMail() function does not work in the Strategy Tester.
861
Common Functions
Sleep
The function suspends execution of the current Expert Advisor or script within a specified interval.
void Sleep(
int milliseconds
// interval
);
Parameters
milliseconds
[in] Delay interval in milliseconds.
Return Value
No return value.
Note
The 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.
862
Common Functions
TerminalClose
The function commands the terminal to complete operation.
bool TerminalClose(
int ret_code
);
Parameters
ret_code
[in] Return code, returned by the process of the client terminal at the operation completion.
Return Value
The function returns true on success, otherwise - false.
Note
The TerminalClose() function does not stop the terminal immediately, it just commands the terminal
to complete its operation.
The code of an Expert Advisor that called TerminalClose() must have all arrangements for the
immediate completion (e.g. all previously opened files must be closed in the normal mode). Call of
this function must be followed by the return operator.
The ret_code parameter allows indicating the necessary return code for analyzing reasons of the
program termination of the terminal operation when starting it from the command prompt.
Example:
//--- input parameters
input int
input int
pips_to_go=15;
// distance in pips
input int
seconds_st=50;
//--- globals
datetime
launch_time;
int
tick_counter=0;
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--Print(__FUNCTION__," reason code = ",reason);
Comment("");
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
static double first_bid=0.0;
863
Common Functions
MqlTick
tick;
double
distance;
//--SymbolInfoTick(_Symbol,tick);
tick_counter++;
if(first_bid==0.0)
{
launch_time=tick.time;
first_bid=tick.bid;
Print("first_bid =",first_bid);
return;
}
//--- price distance in pips
distance=(tick.bid-first_bid)/_Point;
//--- show a notification to track the EA operation
string comm="From the moment of start:\r\n\x25CF elapsed seconds: "+
IntegerToString(tick.time-launch_time)+" ;"+
"\r\n\x25CF ticks received: "+(string)tick_counter+" ;"+
"\r\n\x25CF price went in points: "+StringFormat("%G",distance);
Comment(comm);
//--- section for checking condition to close the terminal
if(tick_counter>=tiks_before)
TerminalClose(0);
if(distance>pips_to_go)
TerminalClose(1);
if(distance<-pips_to_go)
TerminalClose(-1);
if(tick.time-launch_time>seconds_st)
TerminalClose(100);
// termination by timeout
//--}
See also
Program running, Execution errors, Reasons for deinitialization
864
Common Functions
TesterStatistics
The function returns the value of the specified statistical parameter calculated based on testing
results.
double TesterStatistics(
ENUM_STATISTICS statistic_id
// ID
);
Parameters
statistic_id
[in] The ID of the statistical parameter from the ENUM_STATISTICS enumeration.
Return Value
The value of the statistical parameter from testing results.
Note
The function can be called inside OnTester() or OnDeinit() in the tester. In other cases the result is
undefined.
865
Common Functions
TesterWithdrawal
The special function to emulate the operation of money withdrawal in the process of testing. Can be
used in some asset management systems.
bool TesterWithdrawal(
double money
);
Parameters
money
[in] The sum of money that we need to withdraw (in the deposit currency).
Return Value
If successful, returns true, otherwise - false.
866
Common Functions
WebRequest
The function sends an HTTP request to a specified server. The function has two versions:
1. Sending simple requests of type "key=value" using the header Content-Type: application/x-wwwform-urlencoded.
int WebRequest(
const string
method,
// HTTP method
const string
url,
// URL
const string
cookie,
// cookie
const string
referer,
// referer
int
timeout,
const char
&data[],
int
data_size,
char
&result[],
string
&result_headers
// timeout
// the array of the HTTP message body
// data[] array size in bytes
);
2. Sending a request of any type specifying the custom set of headers for a more flexible interaction
with various Web services.
int WebRequest(
const string
method,
// HTTP method
const string
url,
// URL
const string
headers,
int
timeout,
const char
&data[],
char
&result[],
string
&result_headers
// headers
// timeout
);
Parameters
method
[in] HTTP method.
url
[in] URL.
headers
[in] Request headers of type "key: value", separated by a line break "\r\n".
cookie
[in] Cookie value.
referer
[in] Value of the Referer header of the HTTP request.
timeout
[in] Timeout in milliseconds.
867
Common Functions
data[]
[in] Data array of the HTTP message body.
data_size
[in] Size of the data[] array.
result[]
[out] An array containing server response data.
result_headers
[out] Server response headers.
Return Value
HTTP server response code or -1 for an error.
Note
To use the WebRequest() function, add the addresses of the required servers in the list of allowed
URLs in the "Expert Advisors" tab of the "Options" window. Server port is automatically selected on
the basis of the specified protocol - 80 for "http://" and 443 for "https://".
The WebRequest() function is synchronous, which means its breaks the program execution and waits
for the response from the requested server. Since the delays in receiving a response can be large,
the function is not available for calls from the indicators, because indicators run in a common thread
shared by all indicators and charts on one symbol. Indicator performance delay on one of the charts
of a symbol may stop updating of all charts of the same symbol.
The function can be called only from Expert Advisors and scripts, as they run in their own execution
threads. If you try to call the function from an indicator, GetLastError() will return error 4014
"Function is not allowed for call".
WebRequest() cannot be executed in the Strategy Tester.
An example of using the first version of the WebRequest () function:
void OnStart()
{
string cookie=NULL,headers;
char post[],result[];
int res;
//--- to enable access to the server, you should add URL "https://www.google.com/finance"
//--- in the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
string google_url="https://www.google.com/finance";
//--- Reset the last error code
ResetLastError();
//--- Loading a html page from Google Finance
int timeout=5000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection
res=WebRequest("GET",google_url,cookie,NULL,timeout,post,0,result,headers);
//--- Checking errors
if(res==-1)
{
Print("Error in WebRequest. Error code
=",GetLastError());
868
Common Functions
//--- Perhaps the URL is not listed, display a message about the necessity to add the address
MessageBox("Add the address '"+google_url+"' in the list of allowed URLs on tab 'Expert Advis
}
else
{
//--- Load successfully
PrintFormat("The file has been successfully loaded, File size =%d bytes.",ArraySize(result));
//--- Save the data to a file
int filehandle=FileOpen("GoogleFinance.htm",FILE_WRITE|FILE_BIN);
//--- Checking errors
if(filehandle!=INVALID_HANDLE)
{
//--- Save the contents of the result[] array to a file
FileWriteArray(filehandle,result,0,ArraySize(result));
//--- Close the file
FileClose(filehandle);
}
else Print("Error in FileOpen. Error code=",GetLastError());
}
}
"https://www.mql5.com"
#property version
"1.00"
#property strict
#property script_show_inputs
#property description "Sample script posting a user message "
#property description "on the wall on mql5.com"
input string InpLogin
="";
//+------------------------------------------------------------------+
//| Posting a message with an image on the wall at mql5.com
//+------------------------------------------------------------------+
bool PostToNewsFeed(string login,string password,string text,string filename,string filetype)
{
int
res;
char
data[];
char
file[];
string str="Login="+login+"&Password="+password;
string auth,sep="-------Jyecslin9mp8RdKV"; // multipart data separator
//--- A file is available, try to read it
if(filename!=NULL && filename!="")
{
res=FileOpen(filename,FILE_READ|FILE_BIN);
869
Common Functions
if(res<0)
{
Print("Error opening the file \""+filename+"\"");
return(false);
}
//--- Read file data
if(FileReadArray(res,file)!=FileSize(res))
{
FileClose(res);
Print("Error reading the file \""+filename+"\"");
return(false);
}
//--FileClose(res);
}
//--- Create the body of the POST request for authorization
ArrayResize(data,StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8)-1);
//--- Resetting error code
ResetLastError();
//--- Authorization request
res=WebRequest("POST","https://www.mql5.com/en/auth_login",NULL,0,data,data,str);
//--- If authorization failed
if(res!=200)
{
Print("Authorization error #"+(string)res+", LastError="+(string)GetLastError());
return(false);
}
//--- Read the authorization cookie from the server response header
res=StringFind(str,"Set-Cookie: auth=");
//--- If cookie not found, return an error
if(res<0)
{
Print("Error, authorization data not found in the server response (check login/password)");
return(false);
}
//--- Remember the authorization data and form the header for further requests
auth=StringSubstr(str,res+12);
auth="Cookie: "+StringSubstr(auth,0,StringFind(auth,";")+1)+"\r\n";
//--- If there is a data file, send it to the server
if(ArraySize(file)!=0)
{
//--- Form the request body
str="--"+sep+"\r\n";
870
Common Functions
//--- Form the request header
str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
//--- Reset error code
ResetLastError();
//--- Request to send an image file to the server
res=WebRequest("POST","https://www.mql5.com/upload_file",str,0,data,data,str);
//--- check the request result
if(res!=200)
{
=StringFind(str,"\"",8);
filename=StringSubstr(str,8,res-8);
//--- If file uploading fails, an empty link will be returned
if(filename=="")
{
Print("File sending to server failed");
return(false);
}
}
}
//--- Create the body of a request to post an image on the server
str ="--"+sep+"\r\n";
str+="Content-Disposition: form-data; name=\"content\"\r\n\r\n";
str+=text+"\r\n";
//--- The languages in which the post will be available on mql5.com
str+="--"+sep+"\r\n";
str+="Content-Disposition: form-data; name=\"AllLanguages\"\r\n\r\n";
str+="on\r\n";
//--- If the picture has been uploaded on the server, pass its link
if(ArraySize(file)!=0)
{
str+="--"+sep+"\r\n";
str+="Content-Disposition: form-data; name=\"attachedImage_0\"\r\n\r\n";
str+=filename+"\r\n";
}
//--- The final string of the multipart request
str+="--"+sep+"--\r\n";
//--- Out the body of the POST request together in one string
StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8);
ArrayResize(data,ArraySize(data)-1);
//--- Prepare the request header
str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
//--- Request to post a message on the user wall at mql5.com
871
Common Functions
res=WebRequest("POST","https://www.mql5.com/ru/users/"+login+"/wall",str,0,data,data,str);
//--- Return true for successful execution
return(res==200);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Post a message on mql5.com, including an image, the path to which is taken from the InpFileNa
PostToNewsFeed(InpLogin,InpPassword,"Checking the expanded version of WebRequest\r\n"
872
Common Functions
ZeroMemory
The function resets a variable passed to it by reference.
void ZeroMemory(
void& variable
// reset variable
);
Parameters
variable
[in] [out] Variable passed by reference, you want to reset (initialize by zero values).
Return Value
No return value.
Note
If the function parameter is a string, the call will be equivalent to indicating NULL as its value.
For simple types and their arrays, as well as for structures/classes consisting of such types, this is a
simple reset.
For objects containing strings and dynamic arrays, ZeroMemory() is called for each element.
For any arrays not protected by the const modifier, this is the zeroing of all elements.
For arrays of complex objects, ZeroMemory() is called for each element.
ZeroMemory() can't be applied to classes with protected members or inheritance.
873
Array Functions
Action
ArrayBsearch
ArrayCopy
ArrayCompare
ArrayFree
ArrayGetAsSeries
ArrayInitialize
ArrayFill
ArrayIsSeries
ArrayIsDynamic
ArrayMaximum
ArrayMinimum
ArrayRange
ArrayResize
ArraySetAsSeries
ArraySize
ArraySort
in
the
874
Array Functions
ArrayBsearch
Searches for a specified value in a multidimensional numeric array sorted ascending. Search is
performed through the elements of the first dimension.
For searching in an array of double type
int ArrayBsearch(
const double&
array[],
double
value
);
array[],
float
value
);
array[],
long
value
);
array[],
int
value
);
array[],
short
value
);
array[],
value
);
Parameters
array[]
[in] Numeric array for search.
value
875
Array Functions
[in] Value for search.
Return Value
The function returns index of a found element. If the wanted value isn't found, the function returns
the index of an element nearest in value.
Note
Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort() function.
Example:
#property description "Script based on RSI indicator data displays"
#property description "how often the market was in"
#property description "overbought and oversold areas in the specified time interval."
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input int
InpMAPeriod=14;
// Price type
input double
InpOversoldValue=30.0;
// Oversold level
input double
InpOverboughtValue=70.0;
// Overbought level
input datetime
InpDateStart=D'2012.01.01 00:00';
input datetime
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
double rsi_buff[]; // array of the indicator values
int
size=0;
// array size
876
Array Functions
ResetLastError();
if(CopyBuffer(rsi_handle,0,InpDateStart,InpDateFinish,rsi_buff)==-1)
{
PrintFormat("Failed to copy the indicator values. Error code = %d",GetLastError());
return;
}
//--- receive the array size
size=ArraySize(rsi_buff);
//--- sort out the array
ArraySort(rsi_buff);
//--- find out the time (in percentage terms) the market was in the oversold area
double ovs=(double)ArrayBsearch(rsi_buff,InpOversoldValue)*100/(double)size;
//--- find out the time (in percentage terms) the market was in the overbought area
double ovb=(double)(size-ArrayBsearch(rsi_buff,InpOverboughtValue))*100/(double)size;
//--- form the strings for displaying the data
string str="From "+TimeToString(InpDateStart,TIME_DATE)+" to "
+TimeToString(InpDateFinish,TIME_DATE)+" the market was:";
string str_ovb="in overbought area "+DoubleToString(ovb,2)+"% of time";
string str_ovs="in oversold area "+DoubleToString(ovs,2)+"% of time";
//--- display the data on the chart
CreateLabel("top",5,60,str,clrDodgerBlue);
CreateLabel("overbought",5,35,str_ovb,clrDodgerBlue);
CreateLabel("oversold",5,10,str_ovs,clrDodgerBlue);
//--- redraw the chart
ChartRedraw(0);
//--- pause
Sleep(10000);
}
//+------------------------------------------------------------------+
//| Display comment in the bottom left corner of the chart
//+------------------------------------------------------------------+
void CreateLabel(const string name,const int x,const int y,
const string str,const color clr)
{
//--- create the label
ObjectCreate(0,name,OBJ_LABEL,0,0,0);
//--- bind the label to the bottom left corner
ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_LOWER);
//--- change position of the anchor point
ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_LEFT_LOWER);
//--- distance from the anchor point in X-direction
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
//--- distance from the anchor point in Y-direction
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
//--- label text
ObjectSetString(0,name,OBJPROP_TEXT,str);
//--- text color
ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
//--- text size
877
Array Functions
ObjectSetInteger(0,name,OBJPROP_FONTSIZE,12);
}
878
Array Functions
ArrayCopy
It copies an array into another one.
int ArrayCopy(
void&
dst_array[],
// destination array
// source array
int
dst_start=0,
int
src_start=0,
int
count=WHOLE_ARRAY
// number of elements
);
Parameters
dst_array[]
[out] Destination array
src_array[]
[in] Source array
dst_start=0
[in] Starting index from 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.
count=WHOLE_ARRAY
[in] Number of elements that should be copied. By default, the whole array is copied
(count=WHOLE_ARRAY).
Return Value
It returns the number of copied elements.
Note
If count<0 or count>src_size-src_start, all the remaining array part is copied. Arrays are copied from
left to right. For series arrays, the starting position is correctly defined adjusted for copying from
left to right. If 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.
For dynamic arrays with indexing as in timeseries, the size of a destination array is automatically
increased to the amount of copied data (if the latter exceeds the array size). The destination array
size is not decreased automatically.
Example:
#property description "The indicator highlights the candlesticks that are local"
#property description "highs and lows. Interval length for finding"
#property description "extreme values should be found using an input parameters."
879
Array Functions
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots
//---- plot
#property indicator_label1
"Extremums"
#property indicator_type1
DRAW_COLOR_CANDLES
#property indicator_color1
clrLightSteelBlue,clrRed,clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
int
//+------------------------------------------------------------------+
//| Filling out non-extremum candlesticks
//+------------------------------------------------------------------+
void FillCandles(const double &open[],const double &high[],
const double &low[],const double &close[])
{
//--- fill out the candlesticks
ArrayCopy(ExtOpen,open,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtHigh,high,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtLow,low,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtClose,close,ExtStart,ExtStart,ExtCount);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ExtOpen);
SetIndexBuffer(1,ExtHigh);
SetIndexBuffer(2,ExtLow);
SetIndexBuffer(3,ExtClose);
SetIndexBuffer(4,ExtColor,INDICATOR_COLOR_INDEX);
//--- specify the value, which is not displayed
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,INDICATOR_EMPTY_VALUE);
//--- specify the names of indicator buffers for displaying in the data window
880
Array Functions
PlotIndexSetString(0,PLOT_LABEL,"Open;High;Low;Close");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- set straight indexing in time series
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
//--- variable of the bar calculation start
int start=prev_calculated;
//--- calculation is not performed for the first InpNum*2 bars
if(start==0)
{
start+=InpNum*2;
ExtStart=0;
ExtCount=0;
}
//--- if the bar has just formed, check the next potential extremum
if(rates_total-start==1)
start--;
//--- bar index to be checked for the extremum
int ext;
//--- indicator value calculation loop
for(int i=start;i<rates_total-1;i++)
{
//--- initially on i bar without drawing
ExtOpen[i]=0;
ExtHigh[i]=0;
ExtLow[i]=0;
ExtClose[i]=0;
//--- extremum index for check
ext=i-InpNum;
//--- check for the local maximum
if(IsMax(high,ext))
881
Array Functions
{
//--- highlight an extremum candlestick
ExtOpen[ext]=open[ext];
ExtHigh[ext]=high[ext];
ExtLow[ext]=low[ext];
ExtClose[ext]=close[ext];
ExtColor[ext]=1;
//--- highlight other candles up to the extremum with a neutral color
FillCandles(open,high,low,close);
//--- change the variable colors
ExtStart=ext+1;
ExtCount=0;
//--- pass to the next iteration
continue;
}
//--- check for the local minimum
if(IsMin(low,ext))
{
//--- highlight an extremum candlestick
ExtOpen[ext]=open[ext];
ExtHigh[ext]=high[ext];
ExtLow[ext]=low[ext];
ExtClose[ext]=close[ext];
ExtColor[ext]=2;
//--- highlight other candles up to the extremum with a neutral color
FillCandles(open,high,low,close);
//--- change variable values
ExtStart=ext+1;
ExtCount=0;
//--- pass to the next iteration
continue;
}
//--- increase the number of non-extremums at the interval
ExtCount++;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check if the current array element is a local high
//+------------------------------------------------------------------+
bool IsMax(const double &price[],const int ind)
{
//--- interval start variable
int i=ind-InpNum;
//--- interval end period
int finish=ind+InpNum+1;
//--- check for the first half of the interval
for(;i<ind;i++)
882
Array Functions
{
if(price[ind]<=price[i])
return(false);
}
//--- check for the second half of the interval
for(i=ind+1;i<finish;i++)
{
if(price[ind]<=price[i])
return(false);
}
//--- this is an extremum
return(true);
}
//+------------------------------------------------------------------+
//| Check if the current array element is a local low
//+------------------------------------------------------------------+
bool IsMin(const double &price[],const int ind)
{
//--- interval start variable
int i=ind-InpNum;
//--- interval end variable
int finish=ind+InpNum+1;
//--- check for the first half of the interval
for(;i<ind;i++)
{
if(price[ind]>=price[i])
return(false);
}
//--- check for the second half of the interval
for(i=ind+1;i<finish;i++)
{
if(price[ind]>=price[i])
return(false);
}
//--- this is an extremum
return(true);
}
883
Array Functions
ArrayCompare
The function returns the result of comparing two arrays of the same type. It can be used to compare
arrays of simple types or custom structures without complex objects, that is the custom structures
that do not contain strings, dynamic arrays, classes and other structures with complex objects.
int ArrayCompare(
const void& array1[],
// first array
// second array
int
start1=0,
int
start2=0,
int
count=WHOLE_ARRAY
);
Parameters
array1[]
[in] First array.
array2[]
[in] Second array.
start1=0
[in] The element's initial index in the first array, from which comparison starts. The default start
index - 0.
start2=0
[in] The element's initial index in the second array, from which comparison starts. The default
start index - 0.
count=WHOLE_ARRAY
[in] Number of elements to be compared. All elements of both arrays participate in comparison by
default (count=WHOLE_ARRAY).
Return Value
-1, if array1[] less than array2[]
0, if array1[] equal to array2[]
1, if array1[] more than array2[]
-2, if an error occurs due to incompatibility of the types of compared arrays or if start1, start2 or
884
Array Functions
ArrayFree
It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.
void ArrayFree(
void& array[]
// array
);
Parameters
array[]
[in] Dynamic array.
Return Value
No return value.
Note
The need for using ArrayFree() function may not appear too often considering that all used memory
is freed at once and main work with the arrays comprises the access to the indicator buffers. The
sizes of the buffers are automatically managed by the terminal's executive subsystem.
In case it is necessary to manually manage the memory in complex dynamic environment of the
application, ArrayFree() function allows users to free the memory occupied by the already
unnecessary dynamic array explicitly and immediately.
Example:
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
#include <Controls\Label.mqh>
#include <Controls\ComboBox.mqh>
//--- predefined constants
#define X_START 0
#define Y_START 0
#define X_SIZE 280
#define Y_SIZE 300
//+------------------------------------------------------------------+
//| Dialog class for working with memory
//+------------------------------------------------------------------+
class CMemoryControl : public CAppDialog
{
private:
//--- array size
int
m_arr_size;
//--- arrays
char
m_arr_char[];
int
m_arr_int[];
float
m_arr_float[];
double
m_arr_double[];
long
m_arr_long[];
885
Array Functions
//--- labels
CLabel
m_lbl_memory_physical;
CLabel
m_lbl_memory_total;
CLabel
m_lbl_memory_available;
CLabel
m_lbl_memory_used;
CLabel
m_lbl_array_size;
CLabel
m_lbl_array_type;
CLabel
m_lbl_error;
CLabel
m_lbl_change_type;
CLabel
m_lbl_add_size;
//--- buttons
CButton
m_button_add;
CButton
m_button_free;
m_combo_box_step;
CComboBox
m_combo_box_type;
//--- current value of the array type from the combo box
int
m_combo_box_type_value;
public:
CMemoryControl(void);
~CMemoryControl(void);
//--- class object creation method
virtual bool
protected:
//--- create labels
bool
bool
CreateComboBoxStep(void);
bool
CreateComboBoxType(void);
OnClickButtonAdd(void);
void
OnClickButtonFree(void);
void
OnChangeComboBoxType(void);
CurrentArrayFree(void);
bool
CurrentArrayAdd(void);
};
//+------------------------------------------------------------------+
//| Free memory of the current array
//+------------------------------------------------------------------+
void CMemoryControl::CurrentArrayFree(void)
{
//--- reset array size
m_arr_size=0;
886
Array Functions
//--- free the array
if(m_combo_box_type_value==0)
ArrayFree(m_arr_char);
if(m_combo_box_type_value==1)
ArrayFree(m_arr_int);
if(m_combo_box_type_value==2)
ArrayFree(m_arr_float);
if(m_combo_box_type_value==3)
ArrayFree(m_arr_double);
if(m_combo_box_type_value==4)
ArrayFree(m_arr_long);
}
//+------------------------------------------------------------------+
//| Attempt to add memory for the current array
//+------------------------------------------------------------------+
bool CMemoryControl::CurrentArrayAdd(void)
{
//--- exit if the size of the used memory exceeds the size of the physical memory
if(TerminalInfoInteger(TERMINAL_MEMORY_PHYSICAL)/TerminalInfoInteger(TERMINAL_MEMORY_USED)<2)
return(false);
//--- attempt to allocate memory according to the current type
if(m_combo_box_type_value==0 && ArrayResize(m_arr_char,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==1 && ArrayResize(m_arr_int,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==2 && ArrayResize(m_arr_float,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==3 && ArrayResize(m_arr_double,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==4 && ArrayResize(m_arr_long,m_arr_size)==-1)
return(false);
//--- memory allocated
return(true);
}
//+------------------------------------------------------------------+
//| Handling events
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CMemoryControl)
ON_EVENT(ON_CLICK,m_button_add,OnClickButtonAdd)
ON_EVENT(ON_CLICK,m_button_free,OnClickButtonFree)
ON_EVENT(ON_CHANGE,m_combo_box_type,OnChangeComboBoxType)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor
//+------------------------------------------------------------------+
CMemoryControl::CMemoryControl(void)
{
}
//+------------------------------------------------------------------+
887
Array Functions
//| Destructor
//+------------------------------------------------------------------+
CMemoryControl::~CMemoryControl(void)
{
}
//+------------------------------------------------------------------+
//| Class object creation method
//+------------------------------------------------------------------+
bool CMemoryControl::Create(const long chart,const string name,const int subwin,
const int x1,const int y1,const int x2,const int y2)
{
//--- create base class object
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- prepare strings for labels
if(!CreateLabel(m_lbl_memory_physical,"physical_label",X_START+10,Y_START+5,str_physical,12,clrB
return(false);
if(!CreateLabel(m_lbl_memory_total,"total_label",X_START+10,Y_START+30,str_total,12,clrBlack))
return(false);
if(!CreateLabel(m_lbl_memory_available,"available_label",X_START+10,Y_START+55,str_available,12,
return(false);
if(!CreateLabel(m_lbl_memory_used,"used_label",X_START+10,Y_START+80,str_used,12,clrBlack))
return(false);
if(!CreateLabel(m_lbl_change_type,"change_type_label",X_START+10,Y_START+185,"Change type",10,cl
return(false);
if(!CreateLabel(m_lbl_add_size,"add_size_label",X_START+10,Y_START+210,"Add to array",10,clrBlac
return(false);
//--- create control elements
if(!CreateButton(m_button_add,"add_button",X_START+15,Y_START+245,"Add",12,clrBlue))
return(false);
if(!CreateButton(m_button_free,"free_button",X_START+75,Y_START+245,"Free",12,clrBlue))
return(false);
if(!CreateComboBoxType())
return(false);
if(!CreateComboBoxStep())
return(false);
//--- initialize the variable
m_arr_size=0;
888
Array Functions
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create the button
//+------------------------------------------------------------------+
bool CMemoryControl::CreateButton(CButton &button,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create the button
if(!button.Create(m_chart_id,name,m_subwin,x,y,x+50,y+20))
return(false);
//--- text
if(!button.Text(str))
return(false);
//--- font size
if(!button.FontSize(font_size))
return(false);
//--- label color
if(!button.Color(clr))
return(false);
//--- add the button to the control elements
if(!Add(button))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array size
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxStep(void)
{
//--- create the combo box
if(!m_combo_box_step.Create(m_chart_id,"step_combobox",m_subwin,X_START+100,Y_START+185,X_START+
return(false);
//--- add elements to the combo box
if(!m_combo_box_step.ItemAdd("100 000",100000))
return(false);
if(!m_combo_box_step.ItemAdd("1 000 000",1000000))
return(false);
if(!m_combo_box_step.ItemAdd("10 000 000",10000000))
return(false);
if(!m_combo_box_step.ItemAdd("100 000 000",100000000))
return(false);
//--- set the current combo box element
if(!m_combo_box_step.SelectByValue(1000000))
return(false);
//--- add the combo box to control elements
889
Array Functions
if(!Add(m_combo_box_step))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array type
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxType(void)
{
//--- create the combo box
if(!m_combo_box_type.Create(m_chart_id,"type_combobox",m_subwin,X_START+100,Y_START+210,X_START+
return(false);
//--- add elements to the combo box
if(!m_combo_box_type.ItemAdd("char",0))
return(false);
if(!m_combo_box_type.ItemAdd("int",1))
return(false);
if(!m_combo_box_type.ItemAdd("float",2))
return(false);
if(!m_combo_box_type.ItemAdd("double",3))
return(false);
if(!m_combo_box_type.ItemAdd("long",4))
return(false);
//--- set the current combo box element
if(!m_combo_box_type.SelectByValue(3))
return(false);
//--- store the current combo box element
m_combo_box_type_value=3;
//--- add the combo box to control elements
if(!Add(m_combo_box_type))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a label
//+------------------------------------------------------------------+
bool CMemoryControl::CreateLabel(CLabel &lbl,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create a label
if(!lbl.Create(m_chart_id,name,m_subwin,x,y,0,0))
return(false);
//--- text
if(!lbl.Text(str))
return(false);
//--- font size
890
Array Functions
if(!lbl.FontSize(font_size))
return(false);
//--- color
if(!lbl.Color(clr))
return(false);
//--- add the label to control elements
if(!Add(lbl))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Handler of clicking "Add" button event
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonAdd(void)
{
//--- increase the array size
m_arr_size+=(int)m_combo_box_step.Value();
//--- attempt to allocate memory for the current array
if(CurrentArrayAdd())
{
//--- memory allocated, display the current status on the screen
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonFree(void)
{
//--- free the memory of the current array
CurrentArrayFree();
//--- display the current status on the screen
891
Array Functions
//| Handler of the combo box change event
//+------------------------------------------------------------------+
void CMemoryControl::OnChangeComboBoxType(void)
{
//--- check if the array's type has changed
if(m_combo_box_type.Value()!=m_combo_box_type_value)
{
//--- free the memory of the current array
OnClickButtonFree();
//--- work with another array type
m_combo_box_type_value=(int)m_combo_box_type.Value();
//--- display the new array type on the screen
if(m_combo_box_type_value==0)
m_lbl_array_type.Text("Array type = char");
if(m_combo_box_type_value==1)
m_lbl_array_type.Text("Array type = int");
if(m_combo_box_type_value==2)
m_lbl_array_type.Text("Array type = float");
if(m_combo_box_type_value==3)
m_lbl_array_type.Text("Array type = double");
if(m_combo_box_type_value==4)
m_lbl_array_type.Text("Array type = long");
}
}
//--- CMemoryControl class object
CMemoryControl ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- create the dialog
if(!ExtDialog.Create(0,"MemoryControl",0,X_START,Y_START,X_SIZE,Y_SIZE))
return(INIT_FAILED);
//--- launch
ExtDialog.Run();
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--ExtDialog.Destroy(reason);
}
//+------------------------------------------------------------------+
//| Expert chart event function
892
Array Functions
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
ExtDialog.ChartEvent(id,lparam,dparam,sparam);
}
893
Array Functions
ArrayGetAsSeries
It checks direction of an array index.
bool ArrayGetAsSeries(
const void& array[]
);
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.
Example:
#property description "Indicator calculates absolute values of the difference between"
#property description "Open and Close or High and Low prices displaying them in a separate subwindo
#property description "as a histrogram."
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
//---- plot
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
void CandleSizeOnBuffer(const int rates_total,const int prev_calculated,
const double &first[],const double &second[],double &buffer[])
{
//--- start variable for calculation of bars
int start=prev_calculated;
894
Array Functions
//--- work at the last bar if the indicator values have already been calculated at the previous tic
if(prev_calculated>0)
start--;
//--- define indexing direction in arrays
bool as_series_first=ArrayGetAsSeries(first);
bool as_series_second=ArrayGetAsSeries(second);
bool as_series_buffer=ArrayGetAsSeries(buffer);
//--- replace indexing direction with direct one if necessary
if(as_series_first)
ArraySetAsSeries(first,false);
if(as_series_second)
ArraySetAsSeries(second,false);
if(as_series_buffer)
ArraySetAsSeries(buffer,false);
//--- calculate indicator values
for(int i=start;i<rates_total;i++)
buffer[i]=MathAbs(first[i]-second[i]);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- bind indicator buffers
SetIndexBuffer(0,ExtBuffer);
//--- set indexing element in the indicator buffer
ArraySetAsSeries(ExtBuffer,InpAsSeries);
//--- check for what prices the indicator is calculated
if(InpPrices)
{
//--- Open and Close prices
PlotIndexSetString(0,PLOT_LABEL,"BodySize");
//--- set the indicator color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrOrange);
}
else
{
//--- High and Low prices
PlotIndexSetString(0,PLOT_LABEL,"ShadowSize");
//--- set the indicator color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrDodgerBlue);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
895
Array Functions
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- calculate the indicator according to the flag value
if(InpPrices)
CandleSizeOnBuffer(rates_total,prev_calculated,open,close,ExtBuffer);
else
CandleSizeOnBuffer(rates_total,prev_calculated,high,low,ExtBuffer);
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries, ArraySetAsSeries
896
Array Functions
ArrayInitialize
The function initializes a numeric array by a preset value.
For initialization of an array of char type
int ArrayInitialize(
char
array[],
// initialized array
char
value
);
array[],
// initialized array
short
value
);
array[],
// initialized array
int
value
);
array[],
// initialized array
long
value
);
array[],
// initialized array
float
value
);
// initialized array
double value
);
array[],
// initialized array
bool
value
);
897
Array Functions
For initialization of an array of uint type
int ArrayInitialize(
uint
array[],
// initialized array
uint
value
);
Parameters
array[]
[out] Numeric array that should be initialized.
value
[in] New value that should be set to all array elements.
Return Value
Number of initialized elements.
Note
The ArrayResize() function allows to set size of an array with a reserve for further expansion
without the physical relocation of memory. It is implemented for the better performance, because
the operations of memory relocation are reasonably slow.
Initialization of the array using ArrayInitialize(array, init_val) doesn't mean the initialization with
the same value of reserve elements allocated for this array. At further expanding of the array using
the ArrayResize() function, the elements will be added at the end of the array, their values will be
undefined and in most cases will not be equal to init_value.
Example:
void OnStart()
{
//--- dynamic array
double array[];
//--- let's set the array size for 100 elements and reserve a buffer for another 10 elements
ArrayResize(array,100,10);
//--- initialize the array elements with EMPTY_VALUE=DBL_MAX value
ArrayInitialize(array,EMPTY_VALUE);
Print("Values of 10 last elements after initialization");
for(int i=90;i<100;i++) printf("array[%d] = %G",i,array[i]);
//--- expand the array by 5 elements
ArrayResize(array,105);
Print("Values of 10 last elements after ArrayResize(array,105)");
//--- values of 5 last elements are obtained from reserve buffer
for(int i=95;i<105;i++) printf("array[%d] = %G",i,array[i]);
}
898
Array Functions
ArrayFill
The function fills an array with the specified value.
void ArrayFill(
void& array[],
// array
int
start,
// starting index
int
count,
void
value
// value
);
Parameters
array[]
[out] Array of simple type (char, uchar, short, ushort, int, uint, long, ulong, bool, color, datetime,
float, double).
start
[in] Starting index. In such a case, specified AS_SERIES flag is ignored.
count
[in] Number of elements to fill.
value
[in] Value to fill the array with.
Return Value
No return value.
Note
When ArrayFill() function is called, normal indexation direction (from left to right) is always implied.
It means that the change of the order of access to the array elements using ArraySetAsSeries()
function is ignored.
A multidimensional array is shown as one-dimensional when processed by ArrayFill() function. For
example, array[2][4] is processed as array[8]. Therefore, you may specify the initial element's index
to be equal to 5 when working with this array. Thus, the call of ArrayFill(array, 5, 2, 3.14) for
array[2][4] fills array[1][1] and array[1][2] elements with 3.14.
Example:
void OnStart()
{
//--- declare dynamic array
int a[];
//--- set size
ArrayResize(a,10);
//--- fill first 5 elements with 123
ArrayFill(a,0,5,123);
//--- fill next 5 elements with 456
ArrayFill(a,5,5,456);
899
Array Functions
//--- show values
for(int i=0;i<ArraySize(a);i++) printf("a[%d] = %d",i,a[i]);
}
900
Array Functions
ArrayIsDynamic
The function checks whether an array is dynamic.
bool ArrayIsDynamic(
const void& array[]
// checked array
);
Parameters
array[]
[in] Checked array.
Return Value
It returns true if the selected array is dynamic, otherwise it returns false.
Example:
#property description "This indicator does not calculate values. It makes a single attempt to"
#property description "apply the call of ArrayFree() function to three arrays: dynamic one, static
#property description "an indicator buffer. Results are shown in Experts journal."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
// dynamic array
ExtFlag=true;
double ExtBuff[];
// flag
// indicator buffer
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- allocate memory for the array
ArrayResize(ExtDynamic,100);
//--- indicator buffers mapping
SetIndexBuffer(0,ExtBuff);
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
901
Array Functions
{
//--- perform a single analysis
if(ExtFlag)
{
//--- attempt to free memory for arrays
//--- 1. Dynamic array
Print("+============================+");
Print("1. Check dynamic array:");
Print("Size before memory is freed = ",ArraySize(ExtDynamic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtDynamic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtDynamic);
Print("Size after memory is freed = ",ArraySize(ExtDynamic));
//--- 2. Static array
Print("2. Check static array:");
Print("Size before memory is freed = ",ArraySize(ExtStatic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtStatic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtStatic);
Print("Size after memory is freed = ",ArraySize(ExtStatic));
//--- 3. Indicator buffer
Print("3. Check indicator buffer:");
Print("Size before memory is freed = ",ArraySize(ExtBuff));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtBuff) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtBuff);
Print("Size after memory is freed = ",ArraySize(ExtBuff));
//--- change the flag value
ExtFlag=false;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries and indicators
902
Array Functions
ArrayIsSeries
The function checks whether an array is a timeseries.
bool ArrayIsSeries(
const void& array[]
// checked array
);
Parameters
array[]
[in] Checked array.
Return Value
It returns true, if a checked array is an array timeseries, otherwise it returns false. Arrays passed as
a parameter to the OnCalculate() function must be checked for the order of accessing the array
elements by ArrayGetAsSeries().
Example:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Label1"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
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[],
903
Array Functions
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--if(ArrayIsSeries(open))
Print("open[] is timeseries");
else
Print("open[] is not timeseries!!!");
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries and indicators
904
Array Functions
ArrayMaximum
Searches for the largest element in the first dimension of a multidimensional numeric array.
int ArrayMaximum(
const void&
array[],
int
start=0,
int
count=WHOLE_ARRAY
);
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
(count=WHOLE_ARRAY).
for search. By
default,
searches
in
the
entire
array
Return Value
The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
Note
The AS_SERIES flag value is taken into account while searching for a maximum.
Functions ArrayMaximum and ArrayMinimum accept any-dimensional arrays as a parameter.
However, searching is always applied to the first (zero) dimension.
Example:
#property description "The indicator displays larger timeframe's candlesticks on the current one."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 16
#property indicator_plots
//---- plot 1
#property indicator_label1
"BearBody"
#property indicator_color1
clrSeaGreen,clrSeaGreen
//---- plot 2
#property indicator_label2
"BearBodyEnd"
#property indicator_color2
clrSeaGreen,clrSeaGreen
//---- plot 3
#property indicator_label3
"BearShadow"
#property indicator_color3
clrSalmon,clrSalmon
//---- plot 4
#property indicator_label4
"BearShadowEnd"
#property indicator_color4
clrSalmon,clrSalmon
905
Array Functions
//---- plot 5
#property indicator_label5
"BullBody"
#property indicator_color5
clrOlive,clrOlive
//---- plot 6
#property indicator_label6
"BullBodyEnd"
#property indicator_color6
clrOlive,clrOlive
//---- plot 7
#property indicator_label7
"BullShadow"
#property indicator_color7
clrSkyBlue,clrSkyBlue
//---- plot 8
#property indicator_label8
"BullShadowEnd"
#property indicator_color8
clrSkyBlue,clrSkyBlue
ExtBearBodyFirst[];
double
ExtBearBodySecond[];
double
ExtBearBodyEndFirst[];
double
ExtBearBodyEndSecond[];
double
ExtBearShadowFirst[];
double
ExtBearShadowSecond[];
double
ExtBearShadowEndFirst[];
double
ExtBearShadowEndSecond[];
ExtBullBodyFirst[];
double
ExtBullBodySecond[];
double
ExtBullBodyEndFirst[];
double
ExtBullBodyEndSecond[];
double
ExtBullShadowFirst[];
double
ExtBullShadowSecond[];
double
ExtBullShadowEndFirst[];
double
ExtBullShadowEndSecond[];
int
ExtSize=0;
int
ExtCount=0;
int
ExtStartPos=0;
bool
ExtStartFlag=true;
datetime ExtCurrentTime[1];
datetime ExtLastTime;
// last time from the larger time frame, for which the calculation is
bool
ExtBearFlag=true;
// flag for defining the order of writing the data to bearish indicato
bool
ExtBullFlag=true;
// flag for defining the order of writing the data to bullish indicato
int
ExtIndexMax=0;
int
ExtIndexMin=0;
int
//--- shift between the candlestick's open and close price for correct drawing
906
Array Functions
const double ExtEmptyBodySize=0.2*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//+------------------------------------------------------------------+
//| Filling the basic part of the candlestick
//+------------------------------------------------------------------+
void FillCandleMain(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
int &index_max,int &index_min)
{
//--- find the index of the maximum and minimum elements in the arrays
index_max=ArrayMaximum(high,ExtStartPos,last-start+1); // maximum in High
index_min=ArrayMinimum(low,ExtStartPos,last-start+1);
// minimum in Low
//--- define how many bars from the current time frame are to be filled out
int count=fill_index-start+1;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- if the candlestick has been bullish before that, clear the values of bullish indicator
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,star
//--- bearish candlestick
ExtDirectionFlag=-1;
//--- generate the candlestick
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
close[last],high[index_max],low[index_min],start,count,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- if the candlestick has been bearish before that, clear the values of bearish indicator
if(ExtDirectionFlag!=1)
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,star
//--- bullish candlestick
ExtDirectionFlag=1;
//--- generate the candlestick
FormCandleMain(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,clos
open[start],high[index_max],low[index_min],start,count,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- if the candlestick has been bullish before that, clear the values of bullish indicator buffer
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,start,c
//--- bearish candlestick
ExtDirectionFlag=-1;
907
Array Functions
//--- if close and open prices are equal, use the shift for correct display
if(high[index_max]!=low[index_min])
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],start,count,ExtBea
else
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,
open[start],open[start]-ExtEmptyBodySize,high[index_max],
high[index_max]-ExtEmptyBodySize,start,count,ExtBearFlag);
}
//+------------------------------------------------------------------+
//| Fill out the end of the candlestick
//+------------------------------------------------------------------+
void FillCandleEnd(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
const int index_max,const int index_min)
{
//--- do not draw in case of a single bar
if(last-start==0)
return;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start],close[last],high[index_max],low[index_min],fill_index,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBullBodyEndFirst,ExtBullBodyEndSecond,ExtBullShadowEndFirst,ExtBullShadowEnd
close[last],open[start],high[index_max],low[index_min],fill_index,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- generate the end of the candlestick
if(high[index_max]!=low[index_min])
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],fill_index,ExtBearF
else
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],high[index_max]-ExtEmptyBodySize,f
}
//+------------------------------------------------------------------+
908
Array Functions
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- check the indicator period
if(!CheckPeriod((int)Period(),(int)InpPeriod))
return(INIT_PARAMETERS_INCORRECT);
//--- display price data in the foreground
ChartSetInteger(0,CHART_FOREGROUND,0,1);
//--- binding indicator buffers
SetIndexBuffer(0,ExtBearBodyFirst);
SetIndexBuffer(1,ExtBearBodySecond);
SetIndexBuffer(2,ExtBearBodyEndFirst);
SetIndexBuffer(3,ExtBearBodyEndSecond);
SetIndexBuffer(4,ExtBearShadowFirst);
SetIndexBuffer(5,ExtBearShadowSecond);
SetIndexBuffer(6,ExtBearShadowEndFirst);
SetIndexBuffer(7,ExtBearShadowEndSecond);
SetIndexBuffer(8,ExtBullBodyFirst);
SetIndexBuffer(9,ExtBullBodySecond);
SetIndexBuffer(10,ExtBullBodyEndFirst);
SetIndexBuffer(11,ExtBullBodyEndSecond);
SetIndexBuffer(12,ExtBullShadowFirst);
SetIndexBuffer(13,ExtBullShadowSecond);
SetIndexBuffer(14,ExtBullShadowEndFirst);
SetIndexBuffer(15,ExtBullShadowEndSecond);
//--- set some property values for creating the indicator
for(int i=0;i<8;i++)
{
PlotIndexSetInteger(i,PLOT_DRAW_TYPE,DRAW_FILLING); // graphical construction type
PlotIndexSetInteger(i,PLOT_LINE_STYLE,STYLE_SOLID); // drawing line style
PlotIndexSetInteger(i,PLOT_LINE_WIDTH,1);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
909
Array Functions
{
//--- in case there are no calculated bars yet
if(prev_calculated==0)
{
//--- receive larger time frame's bars arrival time
if(!GetTimeData())
return(0);
}
//--- set direct indexing
ArraySetAsSeries(time,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(close,false);
//--- start variable for calculation of bars
int start=prev_calculated;
//--- if the bar is generated, recalculate the indicator value on it
if(start!=0 && start==rates_total)
start--;
//--- the loop for calculating the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill i elements of the indicator buffers by empty values
FillIndicatorBuffers(i);
//--- perform calculation for bars starting from InpDateStart date
if(time[i]>=InpDateStart)
{
//--- define position, from which the values are to be displayed, for the first time
if(ExtStartFlag)
{
//--- store the number of the initial bar
ExtStartPos=i;
//--- define the first date from the larger time frame exceeding time[i]
while(time[i]>=ExtTimeBuff[ExtCount])
if(ExtCount<ExtSize-1)
ExtCount++;
//--- change the value of the flag in order not to run into this block again
ExtStartFlag=false;
}
//--- check if there are still any elements in the array
if(ExtCount<ExtSize)
{
//--- wait for the current time frame's value to reach the larger time frame's one
if(time[i]>=ExtTimeBuff[ExtCount])
{
//--- draw the main part of the candlestick (without filling out the area between th
FillCandleMain(open,close,high,low,ExtStartPos,i-1,i-2,ExtIndexMax,ExtIndexMin);
//--- fill out the end of the candlestick (the area between the last and the penulti
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
910
Array Functions
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- increase the array counter
ExtCount++;
}
else
continue;
}
else
{
//--- reset the array values
ResetLastError();
//--- receive the last date from the larger time frame
if(CopyTime(Symbol(),InpPeriod,0,1,ExtCurrentTime)==-1)
{
Print("Data copy error, code = ",GetLastError());
return(0);
}
//--- if the new date is later, stop generating the candlestick
if(ExtCurrentTime[0]>ExtLastTime)
{
//--- clear the area between the last and penultimate bars in the main indicator buf
ClearEndOfBodyMain(i-1);
//--- fill out the area using auxiliary indicator buffers
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- reset price direction flag
ExtDirectionFlag=0;
//--- store the new last date
ExtLastTime=ExtCurrentTime[0];
}
else
{
//--- generate the candlestick
FillCandleMain(open,close,high,low,ExtStartPos,i,i,ExtIndexMax,ExtIndexMin);
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check correctness of the specified indicator period
//+------------------------------------------------------------------+
bool CheckPeriod(int current_period,int high_period)
{
//--- the indicator period should exceed the timeframe on which it is displayed
911
Array Functions
if(current_period>=high_period)
{
Print("Error! The value of the indicator period should exceed the value of the current time f
return(false);
}
//--- if the indicator period is one week or month, the period is correct
if(high_period>32768)
return(true);
//--- convert period values to minutes
if(high_period>30)
high_period=(high_period-16384)*60;
if(current_period>30)
current_period=(current_period-16384)*60;
//--- the indicator period should be multiple of the time frame it is displayed on
if(high_period%current_period!=0)
{
Print("Error! The value of the indicator period should be multiple of the value of the curren
return(false);
}
//--- the indicator period should exceed the time frame it is displayed on 3 or more times
if(high_period/current_period<3)
{
Print("Error! The indicator period should exceed the current time frame 3 or more times!");
return(false);
}
//--- the indicator period is correct for the current time frame
return(true);
}
//+------------------------------------------------------------------+
//| Receive time data from the larger time frame
//+------------------------------------------------------------------+
bool GetTimeData(void)
{
//--- reset the error value
ResetLastError();
//--- copy all data for the current time
if(CopyTime(Symbol(),InpPeriod,InpDateStart,TimeCurrent(),ExtTimeBuff)==-1)
{
//--- receive the error code
int code=GetLastError();
//--- print out the error message
PrintFormat("Data copy error! %s",code==4401
? "History is still being uploaded!"
: "Code = "+IntegerToString(code));
//--- return false to make a repeated attempt to download data
return(false);
}
//--- receive the array size
ExtSize=ArraySize(ExtTimeBuff);
912
Array Functions
//--- set the loop index for the array to zero
ExtCount=0;
//--- set the current candlestick's position on the time frame to zero
ExtStartPos=0;
ExtStartFlag=true;
//--- store the last time value from the larger time frame
ExtLastTime=ExtTimeBuff[ExtSize-1];
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Function forms the main part of the candlestick. Depending on the flag's |
//| value, the function defines what data and arrays are
//+--------------------------------------------------------------------------+
void FormCandleMain(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int start,const int count,const bool flag)
{
//--- check the flag's value
if(flag)
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,fst_value,snd_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,fst_extremum,snd_extremum,start,count);
}
else
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,snd_value,fst_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,snd_extremum,fst_extremum,start,count);
}
}
//+-------------------------------------------------------------------------------+
//| The function forms the end of the candlestick. Depending on the flag's value, |
//| the function defines what data and arrays are
//+-------------------------------------------------------------------------------+
void FormCandleEnd(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int end,bool &flag)
{
//--- check the flag's value
913
Array Functions
if(flag)
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,fst_value,snd_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,fst_extremum,snd_extremum,end);
//--- change the flag's value to the opposite one
flag=false;
}
else
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,snd_value,fst_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,snd_extremum,fst_extremum,end);
//--- change the flag's value to the opposite one
flag=true;
}
}
//+---------------------------------------------------------------------------------+
//| Clear the end of the candlestick (the area between the last and the penultimate |
//| bar)
//+---------------------------------------------------------------------------------+
void ClearEndOfBodyMain(const int ind)
{
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,ind,1);
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,ind,1);
}
//+--------------------------------------------------------------------------+
//| Clear the candlestick
//+--------------------------------------------------------------------------+
void ClearCandle(double &body_fst[],double &body_snd[],double &shadow_fst[],
double &shadow_snd[],const int start,const int count)
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with empty values
ArrayFill(body_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(body_snd,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_snd,start,count,INDICATOR_EMPTY_VALUE);
}
}
//+--------------------------------------------------------------------------+
//| Generate the main part of the candlestick
//+--------------------------------------------------------------------------+
void FormMain(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int start,const int count)
914
Array Functions
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with values
ArrayFill(fst,start,count,fst_value);
ArrayFill(snd,start,count,snd_value);
}
}
//+-----------------------------------------------------------------------------+
//| Generate the end of the candlestick
//+-----------------------------------------------------------------------------+
void FormEnd(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int last)
{
//--- fill indicator buffers with values
ArrayFill(fst,last-1,2,fst_value);
ArrayFill(snd,last-1,2,snd_value);
}
//+------------------------------------------------------------------+
//| Fill i element of the indicator buffers by empty values
//+------------------------------------------------------------------+
void FillIndicatorBuffers(const int i)
{
//--- set an empty value in the cell of the indicator buffers
ExtBearBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
}
915
Array Functions
ArrayMinimum
Searches for the lowest element in the first dimension of a multidimensional numeric array.
int ArrayMinimum(
const void&
array[],
int
start=0,
int
count=WHOLE_ARRAY
);
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
(count=WHOLE_ARRAY).
for search. By
default,
searches
in
the
entire
array
Return Value
The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
Note
The AS_SERIES flag value is taken into account while searching for a minimum.
Functions ArrayMaximum and ArrayMinimum accept any-dimensional arrays as a parameter.
However, searching is always applied to the first (zero) dimension.
Example:
#property description "The indicator displays larger timeframe's candlesticks on the current one."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 16
#property indicator_plots
//---- plot 1
#property indicator_label1
"BearBody"
#property indicator_color1
clrSeaGreen,clrSeaGreen
//---- plot 2
#property indicator_label2
"BearBodyEnd"
#property indicator_color2
clrSeaGreen,clrSeaGreen
//---- plot 3
#property indicator_label3
"BearShadow"
#property indicator_color3
clrSalmon,clrSalmon
//---- plot 4
#property indicator_label4
"BearShadowEnd"
#property indicator_color4
clrSalmon,clrSalmon
916
Array Functions
//---- plot 5
#property indicator_label5
"BullBody"
#property indicator_color5
clrOlive,clrOlive
//---- plot 6
#property indicator_label6
"BullBodyEnd"
#property indicator_color6
clrOlive,clrOlive
//---- plot 7
#property indicator_label7
"BullShadow"
#property indicator_color7
clrSkyBlue,clrSkyBlue
//---- plot 8
#property indicator_label8
"BullShadowEnd"
#property indicator_color8
clrSkyBlue,clrSkyBlue
ExtBearBodyFirst[];
double
ExtBearBodySecond[];
double
ExtBearBodyEndFirst[];
double
ExtBearBodyEndSecond[];
double
ExtBearShadowFirst[];
double
ExtBearShadowSecond[];
double
ExtBearShadowEndFirst[];
double
ExtBearShadowEndSecond[];
ExtBullBodyFirst[];
double
ExtBullBodySecond[];
double
ExtBullBodyEndFirst[];
double
ExtBullBodyEndSecond[];
double
ExtBullShadowFirst[];
double
ExtBullShadowSecond[];
double
ExtBullShadowEndFirst[];
double
ExtBullShadowEndSecond[];
int
ExtSize=0;
int
ExtCount=0;
int
ExtStartPos=0;
bool
ExtStartFlag=true;
datetime ExtCurrentTime[1];
datetime ExtLastTime;
// last time from the larger time frame, for which the calculation is
bool
ExtBearFlag=true;
// flag for defining the order of writing the data to bearish indicato
bool
ExtBullFlag=true;
// flag for defining the order of writing the data to bullish indicato
int
ExtIndexMax=0;
int
ExtIndexMin=0;
int
//--- shift between the candlestick's open and close price for correct drawing
917
Array Functions
const double ExtEmptyBodySize=0.2*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//+------------------------------------------------------------------+
//| Filling the basic part of the candlestick
//+------------------------------------------------------------------+
void FillCandleMain(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
int &index_max,int &index_min)
{
//--- find the index of the maximum and minimum elements in the arrays
index_max=ArrayMaximum(high,ExtStartPos,last-start+1); // maximum in High
index_min=ArrayMinimum(low,ExtStartPos,last-start+1);
// minimum in Low
//--- define how many bars from the current time frame are to be filled out
int count=fill_index-start+1;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- if the candlestick has been bullish before that, clear the values of bullish indicator
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,star
//--- bearish candlestick
ExtDirectionFlag=-1;
//--- generate the candlestick
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
close[last],high[index_max],low[index_min],start,count,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- if the candlestick has been bearish before that, clear the values of bearish indicator
if(ExtDirectionFlag!=1)
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,star
//--- bullish candlestick
ExtDirectionFlag=1;
//--- generate the candlestick
FormCandleMain(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,clos
open[start],high[index_max],low[index_min],start,count,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- if the candlestick has been bullish before that, clear the values of bullish indicator buffer
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,start,c
//--- bearish candlestick
ExtDirectionFlag=-1;
918
Array Functions
//--- if close and open prices are equal, use the shift for correct display
if(high[index_max]!=low[index_min])
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],start,count,ExtBea
else
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,
open[start],open[start]-ExtEmptyBodySize,high[index_max],
high[index_max]-ExtEmptyBodySize,start,count,ExtBearFlag);
}
//+------------------------------------------------------------------+
//| Fill out the end of the candlestick
//+------------------------------------------------------------------+
void FillCandleEnd(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
const int index_max,const int index_min)
{
//--- do not draw in case of a single bar
if(last-start==0)
return;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start],close[last],high[index_max],low[index_min],fill_index,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBullBodyEndFirst,ExtBullBodyEndSecond,ExtBullShadowEndFirst,ExtBullShadowEnd
close[last],open[start],high[index_max],low[index_min],fill_index,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- generate the end of the candlestick
if(high[index_max]!=low[index_min])
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],fill_index,ExtBearF
else
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],high[index_max]-ExtEmptyBodySize,f
}
//+------------------------------------------------------------------+
919
Array Functions
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- check the indicator period
if(!CheckPeriod((int)Period(),(int)InpPeriod))
return(INIT_PARAMETERS_INCORRECT);
//--- display price data in the foreground
ChartSetInteger(0,CHART_FOREGROUND,0,1);
//--- binding indicator buffers
SetIndexBuffer(0,ExtBearBodyFirst);
SetIndexBuffer(1,ExtBearBodySecond);
SetIndexBuffer(2,ExtBearBodyEndFirst);
SetIndexBuffer(3,ExtBearBodyEndSecond);
SetIndexBuffer(4,ExtBearShadowFirst);
SetIndexBuffer(5,ExtBearShadowSecond);
SetIndexBuffer(6,ExtBearShadowEndFirst);
SetIndexBuffer(7,ExtBearShadowEndSecond);
SetIndexBuffer(8,ExtBullBodyFirst);
SetIndexBuffer(9,ExtBullBodySecond);
SetIndexBuffer(10,ExtBullBodyEndFirst);
SetIndexBuffer(11,ExtBullBodyEndSecond);
SetIndexBuffer(12,ExtBullShadowFirst);
SetIndexBuffer(13,ExtBullShadowSecond);
SetIndexBuffer(14,ExtBullShadowEndFirst);
SetIndexBuffer(15,ExtBullShadowEndSecond);
//--- set some property values for creating the indicator
for(int i=0;i<8;i++)
{
PlotIndexSetInteger(i,PLOT_DRAW_TYPE,DRAW_FILLING); // graphical construction type
PlotIndexSetInteger(i,PLOT_LINE_STYLE,STYLE_SOLID); // drawing line style
PlotIndexSetInteger(i,PLOT_LINE_WIDTH,1);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
920
Array Functions
{
//--- in case there are no calculated bars yet
if(prev_calculated==0)
{
//--- receive larger time frame's bars arrival time
if(!GetTimeData())
return(0);
}
//--- set direct indexing
ArraySetAsSeries(time,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(close,false);
//--- start variable for calculation of bars
int start=prev_calculated;
//--- if the bar is generated, recalculate the indicator value on it
if(start!=0 && start==rates_total)
start--;
//--- the loop for calculating the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill i elements of the indicator buffers by empty values
FillIndicatorBuffers(i);
//--- perform calculation for bars starting from InpDateStart date
if(time[i]>=InpDateStart)
{
//--- define position, from which the values are to be displayed, for the first time
if(ExtStartFlag)
{
//--- store the number of the initial bar
ExtStartPos=i;
//--- define the first date from the larger time frame exceeding time[i]
while(time[i]>=ExtTimeBuff[ExtCount])
if(ExtCount<ExtSize-1)
ExtCount++;
//--- change the value of the flag in order not to run into this block again
ExtStartFlag=false;
}
//--- check if there are still any elements in the array
if(ExtCount<ExtSize)
{
//--- wait for the current time frame's value to reach the larger time frame's one
if(time[i]>=ExtTimeBuff[ExtCount])
{
//--- draw the main part of the candlestick (without filling out the area between th
FillCandleMain(open,close,high,low,ExtStartPos,i-1,i-2,ExtIndexMax,ExtIndexMin);
//--- fill out the end of the candlestick (the area between the last and the penulti
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
921
Array Functions
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- increase the array counter
ExtCount++;
}
else
continue;
}
else
{
//--- reset the array values
ResetLastError();
//--- receive the last date from the larger time frame
if(CopyTime(Symbol(),InpPeriod,0,1,ExtCurrentTime)==-1)
{
Print("Data copy error, code = ",GetLastError());
return(0);
}
//--- if the new date is later, stop generating the candlestick
if(ExtCurrentTime[0]>ExtLastTime)
{
//--- clear the area between the last and penultimate bars in the main indicator buf
ClearEndOfBodyMain(i-1);
//--- fill out the area using auxiliary indicator buffers
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- reset price direction flag
ExtDirectionFlag=0;
//--- store the new last date
ExtLastTime=ExtCurrentTime[0];
}
else
{
//--- generate the candlestick
FillCandleMain(open,close,high,low,ExtStartPos,i,i,ExtIndexMax,ExtIndexMin);
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check correctness of the specified indicator period
//+------------------------------------------------------------------+
bool CheckPeriod(int current_period,int high_period)
{
//--- the indicator period should exceed the timeframe on which it is displayed
922
Array Functions
if(current_period>=high_period)
{
Print("Error! The value of the indicator period should exceed the value of the current time f
return(false);
}
//--- if the indicator period is one week or month, the period is correct
if(high_period>32768)
return(true);
//--- convert period values to minutes
if(high_period>30)
high_period=(high_period-16384)*60;
if(current_period>30)
current_period=(current_period-16384)*60;
//--- the indicator period should be multiple of the time frame it is displayed on
if(high_period%current_period!=0)
{
Print("Error! The value of the indicator period should be multiple of the value of the curren
return(false);
}
//--- the indicator period should exceed the time frame it is displayed on 3 or more times
if(high_period/current_period<3)
{
Print("Error! The indicator period should exceed the current time frame 3 or more times!");
return(false);
}
//--- the indicator period is correct for the current time frame
return(true);
}
//+------------------------------------------------------------------+
//| Receive time data from the larger time frame
//+------------------------------------------------------------------+
bool GetTimeData(void)
{
//--- reset the error value
ResetLastError();
//--- copy all data for the current time
if(CopyTime(Symbol(),InpPeriod,InpDateStart,TimeCurrent(),ExtTimeBuff)==-1)
{
//--- receive the error code
int code=GetLastError();
//--- print out the error message
PrintFormat("Data copy error! %s",code==4401
? "History is still being uploaded!"
: "Code = "+IntegerToString(code));
//--- return false to make a repeated attempt to download data
return(false);
}
//--- receive the array size
ExtSize=ArraySize(ExtTimeBuff);
923
Array Functions
//--- set the loop index for the array to zero
ExtCount=0;
//--- set the current candlestick's position on the time frame to zero
ExtStartPos=0;
ExtStartFlag=true;
//--- store the last time value from the larger time frame
ExtLastTime=ExtTimeBuff[ExtSize-1];
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Function forms the main part of the candlestick. Depending on the flag's |
//| value, the function defines what data and arrays are
//+--------------------------------------------------------------------------+
void FormCandleMain(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int start,const int count,const bool flag)
{
//--- check the flag's value
if(flag)
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,fst_value,snd_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,fst_extremum,snd_extremum,start,count);
}
else
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,snd_value,fst_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,snd_extremum,fst_extremum,start,count);
}
}
//+--------------------------------------------------------------------------------+
//| The function forms the end of the candlestick. Depending on the flag's value,
//+--------------------------------------------------------------------------------+
void FormCandleEnd(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int end,bool &flag)
{
//--- check the flag's value
924
Array Functions
if(flag)
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,fst_value,snd_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,fst_extremum,snd_extremum,end);
//--- change the flag's value to the opposite one
flag=false;
}
else
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,snd_value,fst_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,snd_extremum,fst_extremum,end);
//--- change the flag's value to the opposite one
flag=true;
}
}
//+-------------------------------------------------------------------------------------+
//| Clear the end of the candlestick (the area between the last and the penultimate
//| bar)
//+-------------------------------------------------------------------------------------+
void ClearEndOfBodyMain(const int ind)
{
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,ind,1);
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,ind,1);
}
//+------------------------------------------------------------------+
//| Clear the candlestick
//+------------------------------------------------------------------+
void ClearCandle(double &body_fst[],double &body_snd[],double &shadow_fst[],
double &shadow_snd[],const int start,const int count)
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with empty values
ArrayFill(body_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(body_snd,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_snd,start,count,INDICATOR_EMPTY_VALUE);
}
}
//+------------------------------------------------------------------+
//| Generate the main part of the candlestick
//+------------------------------------------------------------------+
void FormMain(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int start,const int count)
925
Array Functions
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with values
ArrayFill(fst,start,count,fst_value);
ArrayFill(snd,start,count,snd_value);
}
}
//+------------------------------------------------------------------+
//| Generate the end of the candlestick
//+------------------------------------------------------------------+
void FormEnd(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int last)
{
//--- fill indicator buffers with values
ArrayFill(fst,last-1,2,fst_value);
ArrayFill(snd,last-1,2,snd_value);
}
//+------------------------------------------------------------------+
//| Fill i element of the indicator buffers by empty values
//+------------------------------------------------------------------+
void FillIndicatorBuffers(const int i)
{
//--- set an empty value in the cell of the indicator buffers
ExtBearBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
}
926
Array Functions
ArrayRange
The function returns the number of elements in a selected array dimension.
int ArrayRange(
const void& array[],
int
// index of dimension
rank_index
);
Parameters
array[]
[in] Checked array.
rank_index
[in] Index of dimension.
Return Value
Number of elements in a selected array dimension.
Note
Since indexes start at zero, the number of the array dimensions is one greater than the index of the
last dimension.
Example:
void OnStart()
{
//--- create four-dimensional array
double array[][5][2][4];
//--- set the size of the zero dimension
ArrayResize(array,10,10);
//--- print dimensions
int temp;
for(int i=0;i<4;i++)
{
//--- receive the size of i dimension
temp=ArrayRange(array,i);
//--- print
PrintFormat("dim = %d, range = %d",i,temp);
}
//--- Result
// dim = 0, range = 10
// dim = 1, range = 5
// dim = 2, range = 2
// dim = 3, range = 4
}
927
Array Functions
ArrayResize
The function sets a new size for the first dimension
int ArrayResize(
void& array[],
int
new_size,
int
reserve_size=0
);
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
The function can be applied only to dynamic arrays. It should be noted that you cannot change the
size of dynamic arrays assigned as indicator buffers by the SetIndexBuffer() function. For indicator
buffers, all operations of resizing are performed by the runtime subsystem of the terminal.
Total amount of elements in the array cannot exceed 2147483647.
With the frequent memory allocation, it is recommended to use a third parameter that sets a
reserve to reduce the number of physical memory allocations. All the subsequent calls of ArrayResize
do not lead to physical reallocation of memory, but only change the size of the first array dimension
within the reserved memory. It should be remembered that the third parameter will be used only
during physical memory allocation. For example:
ArrayResize(arr,1000,1000);
for(int i=1;i<3000;i++)
ArrayResize(arr,i,1000);
In this case the memory will be reallocated twice, first before entering the 2000-element loop (the
array size will be set to 1000), and the second time with i equal to 2000. If we skip the third
parameter, there will be 2000 physical reallocations of memory, which will slow down the program.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
928
Array Functions
{
//--- Counters
ulong start=GetTickCount();
ulong now;
int
count=0;
Test_ArrayResize (EURUSD,H1)
1. ArraySize(arr)=100000 Time=0 ms
929
Array Functions
Test_ArrayResize (EURUSD,H1)
2. ArraySize(arr)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1)
3. ArraySize(arr)=300000 Time=0 ms
Test_ArrayResize (EURUSD,H1)
Test_ArrayResize (EURUSD,H1)
1. ArraySize(slow)=100000 Time=0 ms
Test_ArrayResize (EURUSD,H1)
2. ArraySize(slow)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1)
3. ArraySize(slow)=300000 Time=228511 ms
*/
See also
ArrayInitialize
930
Array Functions
ArraySetAsSeries
The function sets the AS_SERIES flag to a selected object of a dynamic array, and elements will be
indexed like in timeseries.
bool ArraySetAsSeries(
const void& array[],
// array by reference
bool
flag
);
Parameters
array[]
[in][out] Numeric array to set.
flag
[in] Array indexing direction.
Return Value
The function returns true on success, otherwise - false.
Note
The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays (arrays, whose size in
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).
Example: Indicator that shows bar number
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Numeration"
#property indicator_type1
DRAW_LINE
931
Array Functions
#property indicator_color1
CLR_NONE
NumerationBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,NumerationBuffer,INDICATOR_DATA);
//--- set indexing for the buffer like in timeseries
ArraySetAsSeries(NumerationBuffer,true);
//--- set accuracy of showing in DataWindow
IndicatorSetInteger(INDICATOR_DIGITS,0);
//--- how the name of the indicator array is displayed in DataWindow
PlotIndexSetString(0,PLOT_LABEL,"Bar #");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
See also
932
Array Functions
Access to timeseries, ArrayGetAsSeries
933
Array Functions
ArraySize
The function returns the number of elements of a selected array.
int ArraySize(
const void& array[]
// checked array
);
Parameters
array[]
[in] Array of any type.
Return Value
Value of int type.
Note
For a one-dimensional array, the value to be returned by the ArraySize is equal to that of
ArrayRange(array,0).
Example:
void OnStart()
{
//--- create arrays
double one_dim[];
double four_dim[][10][5][2];
//--- sizes
int one_dim_size=25;
int reserve=20;
int four_dim_size=5;
//--- auxiliary variable
int size;
//--- allocate memory without backup
ArrayResize(one_dim,one_dim_size);
ArrayResize(four_dim,four_dim_size);
//--- 1. one-dimensional array
Print("+==========================================================+");
Print("Array sizes:");
Print("1. One-dimensional array");
size=ArraySize(one_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",one_dim_size,size);
//--- 2. multidimensional array
Print("2. Multidimensional array");
size=ArraySize(four_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",four_dim_size,size);
//--- dimension sizes
int d_1=ArrayRange(four_dim,1);
int d_2=ArrayRange(four_dim,2);
int d_3=ArrayRange(four_dim,3);
934
Array Functions
Print("Check:");
Print("Zero dimension = Array size / (First dimension * Second dimension * Third dimension)");
PrintFormat("%d = %d / (%d * %d * %d)",size/(d_1*d_2*d_3),size,d_1,d_2,d_3);
//--- 3. one-dimensional array with memory backup
Print("3. One-dimensional array with memory backup");
//--- double the value
one_dim_size*=2;
//--- allocate memory with backup
ArrayResize(one_dim,one_dim_size,reserve);
//--- print out the size
size=ArraySize(one_dim);
PrintFormat("Size with backup = %d, Actual array size = %d",one_dim_size+reserve,size);
}
935
Array Functions
ArraySort
Sorts the values in the first dimension of a multidimensional numeric array in the ascending order.
bool ArraySort(
void& array[]
);
Parameters
array[]
[in][out] Numeric array for sorting.
Return Value
The function returns true on success, otherwise - false.
Note
An array is always sorted in the ascending order irrespective of the AS_SERIES flag value.
Functions ArraySort and ArrayBSearch accept any-dimensional arrays as a parameter. However,
searching and sorting are always applied to the first (zero) dimension.
Example:
#property description "The indicator analyzes data for the last month and draws all candlesticks wi
#property description "and large tick volumes. The tick volume array is sorted out"
#property description "to define such candlesticks. The candlesticks having the volumes comprising
#property description "per cent of the array are considered small. The candlesticks having the tick
#property description "the last InpBigVolume per cent of the array are considered large."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots
//--- plot
#property indicator_label1
"VolumeFactor"
#property indicator_type1
DRAW_COLOR_CANDLES
#property indicator_color1
clrDodgerBlue,clrOrange
#property indicator_style1
STYLE_SOLID
#property indicator_width1
ExtOpenBuff[];
double
ExtHighBuff[];
double
ExtLowBuff[];
936
Array Functions
double
ExtCloseBuff[];
double
ExtColorBuff[];
ExtLeftBorder=0;
long
ExtRightBorder=0;
//+------------------------------------------------------------------+
//| Receive border values for tick volumes
//+------------------------------------------------------------------+
bool GetVolumeBorders(void)
{
//--- variables
datetime stop_time;
long
buff[];
//+------------------------------------------------------------------+
datetime GetStartTime(const datetime stop_time)
{
//--- convert end time into MqlDateTime type structure variable
MqlDateTime temp;
TimeToStruct(stop_time,temp);
//--- receive the data that is one month less
if(temp.mon>1)
temp.mon-=1;
// the current month is not the first one in the year, therefore, the number of
else
{
temp.mon=12;
// the current month is the first in the year, therefore, the number of the pre
937
Array Functions
temp.year-=1; // while the year number is one less
}
//--- day number will not exceed 28
if(temp.day>28)
temp.day=28;
//--- return the obtained date
return(StructToTime(temp));
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- check if input parameters satisfy the conditions
if(InpSmallVolume<0 || InpSmallVolume>=50 || InpBigVolume<0 || InpBigVolume>=50)
{
Print("Incorrect input parameters");
return(INIT_PARAMETERS_INCORRECT);
}
//--- indicator buffers mapping
SetIndexBuffer(0,ExtOpenBuff);
SetIndexBuffer(1,ExtHighBuff);
SetIndexBuffer(2,ExtLowBuff);
SetIndexBuffer(3,ExtCloseBuff);
SetIndexBuffer(4,ExtColorBuff,INDICATOR_COLOR_INDEX);
//--- set the value that will not be displayed
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,INDICATOR_EMPTY_VALUE);
//--- set labels for indicator buffers
PlotIndexSetString(0,PLOT_LABEL,"Open;High;Low;Close");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- check if unhandled bars are still present
if(prev_calculated<rates_total)
{
938
Array Functions
//--- receive new values of the right and left borders for volumes
if(!GetVolumeBorders())
return(0);
}
//--- start variable for bar calculation
int start=prev_calculated;
//--- work at the last bar if the indicator values have already been calculated at the previous tic
if(start>0)
start--;
//--- set direct indexing in time series
ArraySetAsSeries(time,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
ArraySetAsSeries(tick_volume,false);
//--- the loop of calculation of the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill out candlesticks starting from the initial date
if(ExtStartTime<=time[i])
{
//--- if the value is not less than the right border, fill out the candlestick
if(tick_volume[i]>=ExtRightBorder)
{
//--- receive data for drawing the candlestick
ExtOpenBuff[i]=open[i];
ExtHighBuff[i]=high[i];
ExtLowBuff[i]=low[i];
ExtCloseBuff[i]=close[i];
//--- DodgerBlue color
ExtColorBuff[i]=0;
//--- continue the loop
continue;
}
//--- fill out the candlestick if the value does not exceed the left border
if(tick_volume[i]<=ExtLeftBorder)
{
//--- receive data for drawing the candlestick
ExtOpenBuff[i]=open[i];
ExtHighBuff[i]=high[i];
ExtLowBuff[i]=low[i];
ExtCloseBuff[i]=close[i];
//--- Orange color
ExtColorBuff[i]=1;
//--- continue the loop
continue;
}
}
939
Array Functions
//--- set empty values for bars that have not been included in the calculation
ExtOpenBuff[i]=INDICATOR_EMPTY_VALUE;
ExtHighBuff[i]=INDICATOR_EMPTY_VALUE;
ExtLowBuff[i]=INDICATOR_EMPTY_VALUE;
ExtCloseBuff[i]=INDICATOR_EMPTY_VALUE;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
ArrayBsearch
940
Conversion Functions
Conversion Functions
This is a group of functions that provide conversion of data from one format into another.
The NormalizeDouble() function must be specially noted as it provides the necessary accuracy of the
price presentation. In trading operations, no unnormalized prices may be used if their accuracy even a
digit exceeds that required by the trade server.
Function
Action
CharToString
DoubleToString
EnumToString
NormalizeDouble
StringToDouble
StringToInteger
StringToTime
TimeToString
IntegerToString
ShortToString
ShortArrayToString
StringToShortArray
CharArrayToString
StringToCharArray
ColorToARGB
941
Conversion Functions
ColorToString
StringToColor
StringFormat
See also
Use of a Codepage
942
Conversion Functions
CharToString
Converting a symbol code into a one-character string.
string CharToString(
uchar char_code
);
Parameters
char_code
[in] Code of ANSI symbol.
Return Value
String with a ANSI symbol.
943
Conversion Functions
CharArrayToString
It copies and converts part of array of uchar type into a returned string.
string CharArrayToString(
uchar array[],
// array
int
start=0,
int
count=-1
// number of symbols
uint
codepage=CP_ACP
// code page
);
Parameters
array[]
[in] Array of uchar type.
start=0
[in] Position from which copying starts. by default 0 is used.
count=-1
[in] Number of array elements for copying. Defines the length of a resulting string. Default value
is -1, which means copying up to the array end, or till terminal 0.
codepage=CP_ACP
[in] The value of the code page. There is a number of built-in constants for the most used code
pages.
Return Value
String.
See also
Use of a Codepage
944
Conversion Functions
ColorToARGB
The function converts color type into uint type to get ARGB representation of the color. ARGB color
format is used to generate a graphical resource, text display, as well as for CCanvas standard library
class.
uint ColorToARGB(
color clr,
uchar alpha=255
);
Parameters
clr
[in] Color value in color type variable.
alpha
[in] The value of the alpha channel used to receive the color in ARGB format. The value may be
set from 0 (a color of a foreground pixel does not change the display of an underlying one) up to
255 (a color of an underlying pixel is completely replaced by the foreground pixel's one). Color
transparency in percentage terms is calculated as (1-alpha/255)*100%. In other words, the lesser
value of the alpha channel leads to more transparent color.
Return Value
Presenting the color in ARGB format where Alfa, Red, Green, Blue (alpha channel, red, green, blue)
values are set in series in four uint type bytes.
Note
RGB is a basic and commonly used format for pixel color description on a screen in computer
graphics. Names of basic colors are used to set red, green and blue color components. Each
component is described by one byte specifying the color saturation in the range of 0 to 255 (0x00 to
0XFF in hexadecimal format). Since the white color contains all colors, it is described as 0xFFFFFF,
that is, each one of three components is presented by the maximum value of 0xFF.
However, some tasks require to specify the color transparency to describe the look of an image in
case it is covered by the color with some degree of transparency. The concept of alpha channel is
introduced for such cases. It is implemented as an additional component of RGB format. ARGB
format structure is shown below.
ARGB values are typically expressed using hexadecimal format with each pair of digits representing
the values of Alpha, Red, Green and Blue channels, respectively. For example, 80FFFF00 color
represents 50.2% opaque yellow. Initially, 0x80 sets 50.2% alpha value, as it is 50.2% of 0xFF value.
Then, the first FF pair defines the highest value of the red component; the next FF pair is like the
previous but for the green component; the final 00 pair represents the lowest value the blue
component can have (absence of blue). Combination of green and red colors yields yellow one. If the
alpha channel is not used, the entry can be reduced down to 6 RRGGBB digits, this is why the alpha
945
Conversion Functions
channel values are stored in the top bits of uint integer type.
Depending on the context, hexadecimal digits can be written with '0x' or '#' prefix, for example,
80FFFF00, 0x80FFFF00 or #80FFFF00.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- set transparency
uchar alfa=0x55;
See also
Resources, ResourceCreate(), TextOut(), color type, char, short, int and long types
946
Conversion Functions
ColorToString
It converts color value into string of "R,G,B" form.
string ColorToString(
color color_value,
// color value
bool
color_name
);
Parameters
color_value
[in] Color value in color type variable.
color_name
[in] Return color name if it 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:
string clr=ColorToString(C'0,255,0'); // green color
Print(clr);
clr=ColorToString(C'0,255,0',true);
Print(clr);
947
Conversion Functions
DoubleToString
Converting numeric value into text string.
string DoubleToString(
double value,
// number
int
digits=8
);
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
String containing a symbol representation of a number with the specified accuracy.
Example:
Print("DoubleToString(120.0 + M_PI) : ",DoubleToString(120.0+M_PI));
Print("DoubleToString(120.0 + M_PI,16) : ",DoubleToString(120.0+M_PI,16));
Print("DoubleToString(120.0 + M_PI,-16) : ",DoubleToString(120.0+M_PI,-16));
Print("DoubleToString(120.0 + M_PI,-1) : ",DoubleToString(120.0+M_PI,-1));
Print("DoubleToString(120.0 + M_PI,-20) : ",DoubleToString(120.0+M_PI,-20));
See also
NormalizeDouble, StringToDouble
948
Conversion Functions
EnumToString
Converting an enumeration value of any type to a text form.
string EnumToString(
any_enum 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:
enum interval
{
month=1,
// one-month interval
two_months,
// two months
quarter,
halfyear=6,
// half a year
year=12,
// a year - 12 months
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the time interval equal to one month
interval period=month;
Print(EnumToString(period)+"="+IntegerToString(period));
//--- set the time interval equal to a quarter (three months)
period=quarter;
Print(EnumToString(period)+"="+IntegerToString(period));
//--- set the time interval equal to one year (12 months)
period=year;
Print(EnumToString(period)+"="+IntegerToString(period));
//--- check how the order type is shown
949
Conversion Functions
ENUM_ORDER_TYPE type=ORDER_TYPE_BUY;
Print(EnumToString(type)+"="+IntegerToString(type));
//--- check how incorrect values are shown
type=WRONG_VALUE;
Print(EnumToString(type)+"="+IntegerToString(type));
// Result:
// month=1
// quarter=3
// year=12
// ORDER_TYPE_BUY=0
// ENUM_ORDER_TYPE::-1=-1
}
See also
Enumerations, Input variables
950
Conversion Functions
IntegerToString
This function converts value of integer type into a string of a specified length and returns the obtained
string.
string IntegerToString(
long
number,
// number
int
str_len=0,
// 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.
951
Conversion Functions
ShortToString
It converts the symbol code (unicode) into one-symbol string and returns resulting string.
string ShortToString(
ushort symbol_code
// symbol
);
Parameters
symbol_code
[in] 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.
952
Conversion Functions
ShortArrayToString
It copies part of array into a returned string.
string ShortArrayToString(
ushort array[],
// array
int
start=0,
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.
953
Conversion Functions
TimeToString
Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy.mm.dd
hh:mi" format.
string TimeToString(
datetime value,
// number
int
// output format
mode=TIME_DATE|TIME_MINUTES
);
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:mm",
TIME_SECONDS gets results as "hh:mm:ss".
Return Value
String.
954
Conversion Functions
NormalizeDouble
Rounding floating point number to a specified accuracy.
double NormalizeDouble(
double value,
// normalized number
int
digits
);
Parameters
value
[in] Value with a floating point.
digits
[in] Accuracy format, number of digits after point (0-8).
Return Value
Value of double type with preset accuracy.
Note
Calculated values of 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().
Please note that when output to Journal using the Print() function, a normalized number may contain
a greater number of decimal places than you expect. For example, for:
double a=76.671;
Print("Print(76.671)=",a);
// Output as is
955
Conversion Functions
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,
956
Conversion Functions
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,
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 string, the size of the array
will not be reduced.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide appropriate constants.
Return Value
Number of copied elements.
See also
Use of a Codepage
957
Conversion Functions
StringToColor
Converting "R,G,B" string or string with color name into color type value.
color StringToColor(
string color_string
);
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);
958
Conversion Functions
StringToDouble
The function converts string containing a symbol representation of number into number of double
type.
double StringToDouble(
string value
// string
);
Parameters
value
[in] String containing a symbol representation of a number.
Return Value
Value of double type.
959
Conversion Functions
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
Value of long type.
960
Conversion Functions
StringToShortArray
The function symbol-wise copies a string into a specified place of an array of ushort type. It returns
the number of copied elements.
int StringToShortArray(
string text_string,
// source string
ushort& array[],
// array
int
start=0,
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 string, the size of the array
will not be reduced.
Return Value
Number of copied elements.
961
Conversion Functions
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.
962
Conversion Functions
StringFormat
The function formats obtained parameters and returns a string.
string StringFormat(
string format,
...
// 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.
Example:
963
Conversion Functions
void OnStart()
{
//--- string variables
string output_string;
string temp_string;
string format_string;
//--- prepare the specification header
temp_string=StringFormat("Contract specification for %s:\n",_Symbol);
StringAdd(output_string,temp_string);
//--- int value output
int digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
temp_string=StringFormat("
SYMBOL_DIGITS = %d (number of digits after the decimal point)\n",
digits);
StringAdd(output_string,temp_string);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
format_string=StringFormat("
SYMBOL_POINT = %%.%df (point value)\n",
digits);
temp_string=StringFormat(format_string,point_value);
StringAdd(output_string,temp_string);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
temp_string=StringFormat("
SYMBOL_SPREAD = %d (current spread in points)\n",
spread);
StringAdd(output_string,temp_string);
//--- int value output
int min_stop=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
temp_string=StringFormat("
SYMBOL_TRADE_STOPS_LEVEL = %d (minimal indention in points for Stop
min_stop);
StringAdd(output_string,temp_string);
//--- double value output without the fractional part
double contract_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE);
temp_string=StringFormat("
SYMBOL_TRADE_CONTRACT_SIZE = %.f (contract size)\n",
contract_size);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double tick_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
temp_string=StringFormat("
SYMBOL_TRADE_TICK_SIZE = %f (minimal price change)\n",
tick_size);
StringAdd(output_string,temp_string);
//--- determining the swap calculation mode
int swap_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_SWAP_MODE);
string str_swap_mode;
switch(swap_mode)
{
case SYMBOL_SWAP_MODE_DISABLED: str_swap_mode="SYMBOL_SWAP_MODE_DISABLED (no swaps)"; break;
case SYMBOL_SWAP_MODE_POINTS: str_swap_mode="SYMBOL_SWAP_MODE_POINTS (in points)"; break;
case SYMBOL_SWAP_MODE_CURRENCY_SYMBOL: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_SYMBOL (in mo
case SYMBOL_SWAP_MODE_CURRENCY_MARGIN: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_MARGIN (in mo
case SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT (in
case SYMBOL_SWAP_MODE_INTEREST_CURRENT: str_swap_mode="SYMBOL_SWAP_MODE_INTEREST_CURRENT (as
case SYMBOL_SWAP_MODE_INTEREST_OPEN: str_swap_mode="SYMBOL_SWAP_MODE_INTEREST_OPEN (as the sp
case SYMBOL_SWAP_MODE_REOPEN_CURRENT: str_swap_mode="SYMBOL_SWAP_MODE_REOPEN_CURRENT (by reop
case SYMBOL_SWAP_MODE_REOPEN_BID: str_swap_mode="SYMBOL_SWAP_MODE_REOPEN_BID (by reopening po
}
//--- string value output
temp_string=StringFormat("
SYMBOL_SWAP_MODE = %s\n",
str_swap_mode);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_long=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_LONG);
964
Conversion Functions
temp_string=StringFormat("
SYMBOL_SWAP_LONG = %f (long swap value)\n",
swap_long);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_short=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_SHORT);
temp_string=StringFormat("
SYMBOL_SWAP_SHORT = %f (short swap value)\n",
swap_short);
StringAdd(output_string,temp_string);
//--- determining the trading mode
int trade_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_MODE);
string str_trade_mode;
switch(trade_mode)
{
case SYMBOL_TRADE_MODE_DISABLED: str_trade_mode="SYMBOL_TRADE_MODE_DISABLED (trade is disable
case SYMBOL_TRADE_MODE_LONGONLY: str_trade_mode="SYMBOL_TRADE_MODE_LONGONLY (only long positi
case SYMBOL_TRADE_MODE_SHORTONLY: str_trade_mode="SYMBOL_TRADE_MODE_SHORTONLY (only short pos
case SYMBOL_TRADE_MODE_CLOSEONLY: str_trade_mode="SYMBOL_TRADE_MODE_CLOSEONLY (only position
case SYMBOL_TRADE_MODE_FULL: str_trade_mode="SYMBOL_TRADE_MODE_FULL (no trade restrictions)";
}
//--- string value output
temp_string=StringFormat("
SYMBOL_TRADE_MODE = %s\n",
str_trade_mode);
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_min=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
temp_string=StringFormat("
SYMBOL_VOLUME_MIN = %g (minimal volume for a deal)\n",volume_min);
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
temp_string=StringFormat("
SYMBOL_VOLUME_STEP = %g (minimal volume change step)\n",volume_step
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_max=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
temp_string=StringFormat("
SYMBOL_VOLUME_MAX = %g (maximal volume for a deal)\n",volume_max);
StringAdd(output_string,temp_string);
//--- determining the contract price calculation mode
int calc_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_CALC_MODE);
string str_calc_mode;
switch(calc_mode)
{
case SYMBOL_CALC_MODE_FOREX:str_calc_mode="SYMBOL_CALC_MODE_FOREX (Forex)";break;
case SYMBOL_CALC_MODE_FUTURES:str_calc_mode="SYMBOL_CALC_MODE_FUTURES (futures)";break;
case SYMBOL_CALC_MODE_CFD:str_calc_mode="SYMBOL_CALC_MODE_CFD (CFD)";break;
case SYMBOL_CALC_MODE_CFDINDEX:str_calc_mode="SYMBOL_CALC_MODE_CFDINDEX (CFD for indices)";br
case SYMBOL_CALC_MODE_CFDLEVERAGE:str_calc_mode="SYMBOL_CALC_MODE_CFDLEVERAGE (CFD at leverag
case SYMBOL_CALC_MODE_EXCH_STOCKS:str_calc_mode="SYMBOL_CALC_MODE_EXCH_STOCKS (trading securi
case SYMBOL_CALC_MODE_EXCH_FUTURES:str_calc_mode="SYMBOL_CALC_MODE_EXCH_FUTURES (trading futu
case SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS:str_calc_mode="SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS (
}
//--- string value output
temp_string=StringFormat("
SYMBOL_TRADE_CALC_MODE = %s\n",
str_calc_mode);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_initial=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_INITIAL);
temp_string=StringFormat("
SYMBOL_MARGIN_INITIAL = %.2f (initial margin)\n",
margin_initial);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_maintenance=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_MAINTENANCE);
temp_string=StringFormat("
SYMBOL_MARGIN_MAINTENANCE = %.2f (maintenance margin)\n",
965
Conversion Functions
margin_maintenance);
StringAdd(output_string,temp_string);
//--- int value output
int freeze_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
temp_string=StringFormat("
SYMBOL_TRADE_FREEZE_LEVEL = %d (order freeze level in points)",
freeze_level);
StringAdd(output_string,temp_string);
Print(output_string);
Comment(output_string);
/* execution result
Contract specification for EURUSD:
SYMBOL_DIGITS = 5 (number of digits after the decimal point)
SYMBOL_POINT = 0.00001 (point value)
SYMBOL_SPREAD = 10 (current spread in points)
SYMBOL_TRADE_STOPS_LEVEL = 18 (minimal indention in points for Stop orders)
SYMBOL_TRADE_CONTRACT_SIZE = 100000 (contract size)
SYMBOL_TRADE_TICK_SIZE = 0.000010 (minimal price change)
SYMBOL_SWAP_MODE = SYMBOL_SWAP_MODE_POINTS (in points)
SYMBOL_SWAP_LONG = -0.700000 (buy order swap value)
SYMBOL_SWAP_SHORT = -1.000000 (sell order swap value)
SYMBOL_TRADE_MODE = SYMBOL_TRADE_MODE_FULL (no trade restrictions)
SYMBOL_VOLUME_MIN = 0.01 (minimal volume for a deal)
SYMBOL_VOLUME_STEP = 0.01 (minimal volume change step)
SYMBOL_VOLUME_MAX = 500 (maximal volume for a deal)
SYMBOL_TRADE_CALC_MODE = SYMBOL_CALC_MODE_FOREX (Forex)
SYMBOL_MARGIN_INITIAL = 0.00 (initial margin)
SYMBOL_MARGIN_MAINTENANCE = 0.00 (maintenance margin)
SYMBOL_TRADE_FREEZE_LEVEL = 0 (order freeze level in points)
*/
}
See also
PrintFormat, DoubleToString,ColorToString, TimeToString
966
Math Functions
Mathematical Functions
A set of mathematical and trigonometric functions.
Function
Action
MathAbs
MathArccos
MathArcsin
MathArctan
MathCeil
MathCos
MathExp
MathFloor
MathLog
MathLog10
MathMax
MathMin
MathMod
MathPow
MathRand
MathRound
MathSin
MathSqrt
MathSrand
MathTan
MathIsValidNumber
(modulus)
of
the
967
Math Functions
MathAbs
The function returns the absolute value (modulus) of the specified numeric value.
double MathAbs(
double value
// numeric value
);
Parameters
value
[in] Numeric value.
Return Value
Value of double type more than or equal to zero.
Note
Instead the MathAbs() function you can use fabs().
968
Math Functions
MathArccos
The function returns the arccosine of x within the range 0 to p in radians.
double MathArccos(
double val
// -1<val<1
);
Parameters
val
[in] The val value between -1 and 1, the arc cosine of which is to be calculated.
Return Value
Arc cosine of a number in radians. If val is less than -1 or more than 1, the function returns NaN
(indeterminate value).
Note
Instead of the MathArccos() function you can use acos().
See also
Real types (double, float)
969
Math Functions
MathArcsin
The function returns the arc sine of x within the range of -p /2 to p /2 radians.
double MathArcsin(
double val
// -1<value<1
);
Parameters
val
[in] The val value between -1 and 1, the arc sine of which is to be calculated.
Return Value
Arc sine of the val number in radians within the range of -p /2 to p /2 radians. If val is less than -1
or more than 1, the function returns NaN (indeterminate value).
Note
Instead of the MathArcsin() function you can use asin().
See also
Real types (double, float)
970
Math Functions
MathArctan
The function returns the arc tangent of x. If x is equal to 0, the function returns 0.
double MathArctan(
double value
// tangent
);
Parameters
value
[in] A number representing a tangent.
Return Value
MathArctan returns a value within the range of -p /2 to p /2 radians.
Note
Instead of the MathArctan() function you can use atan().
971
Math Functions
MathCeil
The function returns integer numeric value closest from above.
double MathCeil(
double val
// number
);
Parameters
val
[in] Numeric value.
Return Value
Numeric value representing the smallest integer that exceeds or equals to val.
Note
Instead of the MathCeil() function you can use ceil().
972
Math Functions
MathCos
The function returns the cosine of an angle.
double MathCos(
double value
// number
);
Parameters
value
[in] Angle in radians.
Return Value
Value of double type within the range of -1 to 1.
Note
Instead of MathCos() you can use cos().
973
Math Functions
MathExp
The function returns the value of e raised to the power of d.
double MathExp(
double value
);
Parameters
value
[in] A number specifying the power.
Return Value
A number of double type. In case of overflow the function returns INF (infinity), in case of underflow
MathExp returns 0.
Note
Instead of MathExp() you can use exp().
See also
Real types (double, float)
974
Math Functions
MathFloor
The function returns integer numeric value closest from below.
double MathFloor(
double val
// number
);
Parameters
val
[in] Numeric value.
Return Value
A numeric value representing the largest integer that is less than or equal to val.
Note
Instead of MathFloor() you can use floor().
975
Math Functions
MathLog
The function returns a natural logarithm.
double MathLog(
double val
);
Parameters
val
[in] Value logarithm of which is to be found.
Return Value
The natural logarithm of val in case of success. If val is negative, the function returns NaN
(undetermined value). If val is equal to 0, the function returns INF (infinity).
Note
Instead of MathLog() you can use log().
See also
Real types (double, float)
976
Math Functions
MathLog
Returns the logarithm of a number by base 10.
double MathLog10(
double val
);
Parameters
val
[in] Numeric value the common logarithm of which is to be calculated.
Return Value
The common logarithm in case of success. If val is negative, the function returns NaN
(undetermined value). If val is equal to 0, the function returns INF (infinity).
Note
Instead of MathLog10() you can use log10().
See also
Real types (double, float)
977
Math Functions
MathMax
The function returns the maximal value of two values.
double MathMax(
double value1,
// first value
double value2
// second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
The largest of the two values.
Note
Instead of MathMax() you can use fmax(). Functions fmax(), fmin(), MathMax(), MathMin() can
work with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the smaller type is
automatically cast to the larger type. The type of the return value corresponds to the larger type.
If data of the same type are passed, no casting is performed.
978
Math Functions
MathMin
The function returns the minimal value of two values.
double MathMin(
double value1,
// first value
double value2
// second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
The smallest of the two values.
Note
Instead of MathMin() you can use fmin(). Functions fmax(), fmin(), MathMax(), MathMin() can work
with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the smaller type is
automatically cast to the larger type. The type of the return value corresponds to the larger type.
If data of the same type are passed, no casting is performed.
979
Math Functions
MathMod
The function returns the real remainder of division of two numbers.
double MathMod(
double value,
// dividend value
double value2
// divisor value
);
Parameters
value
[in] Dividend value.
value2
[in] Divisor value.
Return Value
The MathMod function calculates the real remainder f from expression val/y so that val = i * y + f ,
where i is an integer, f has the same sign as val, and the absolute value of f is less than the
absolute value of y.
Note
Instead of MathMod() you can use fmod().
980
Math Functions
MathPow
The function raises a base to a specified power.
double MathPow(
double base,
// base
double exponent
// exponent value
);
Parameters
base
[in] Base.
exponent
[in] Exponent value.
Return Value
Value of base raised to the specified power.
Note
Instead of MathPow() you can use pow().
981
Math Functions
MathRand
Returns a pseudorandom integer within the range of 0 to 32767.
int MathRand();
Return Value
Integer value within the range of 0 to 32767.
Note
Before the first call of the function, it's necessary to call MathSrand to set the generator of
pseudorandom numbers to the initial state.
Note
Instead of MathRand() you can use rand().
982
Math Functions
MathRound
The function returns a value rounded off to the nearest integer of the specified numeric value.
double MathRound(
double value
// value to be rounded
);
Parameters
value
[in] Numeric value before rounding.
Return Value
Value rounded till to the nearest integer.
Note
Instead of MathRound() you can use round().
983
Math Functions
MathSin
Returns the sine of a specified angle.
double MathSin(
double value
// argument in radians
);
Parameters
value
[in] Angle in radians.
Return Value
Sine of an angle measured in radians. Returns value within the range of -1 to 1.
Note
Instead of MathSin() you can use sin().
984
Math Functions
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. If value is negative, MathSqrt returns NaN (indeterminate value).
Note
Instead of MathSqrt() you can use sqrt().
See also
Real types (double, float)
985
Math Functions
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 sequence of random numbers.
Return Value
No return value.
Note
The MathRand() function is used for generating a sequence of pseudorandom numbers. Call of
MathSrand() with a certain initializing number allows to always produces the same sequence of
pseudorandom numbers.
To ensure receipt of non-recurring sequence, use the call of MathSrand(GetTickCount()), since the
value of GetTickCount() increases from the moment of the start of the operating system and is not
repeated within 49 days, until the built-in counter of milliseconds overflows. Use of
MathSrand(TimeCurrent()) is not suitable, because the TimeCurrent() function returns the time of
the last tick, which can be unchanged for a long time, for example at the weekend.
Initialization of the random number generator using MathSrand() for indicators and Expert Advisors
is better performed in the OnInit() handler; it saves you from the following multiple restarts of the
generator in OnTick() and OnCalculate().
Instead of the MathSrand() function you can use the srand() function.
Example:
#property description "The indicator shows the central limit theorem, which states:"
#property description "The sum of a sufficiently large number of weakly dependent random variables,
#property description "having approximately equal magnitude (none of the summands dominates,"
#property description "or makes a determining contribution to the sum), has a distribution close to
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"Label"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrRoyalBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
sample_number=10;
986
Math Functions
double
LabelBuffer[];
ticks_counter;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
void OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,LabelBuffer,INDICATOR_DATA);
//--- turn the indicator buffer around from the present to the past
ArraySetAsSeries(LabelBuffer,true);
//--- Initialize the generator of random numbers
MathSrand(GetTickCount());
//--- Initialize the counter of ticks
ticks_counter=0;
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- For a zero counter reset the indicator buffer
if(ticks_counter==0) ArrayInitialize(LabelBuffer,0);
//--- Increase the counter
ticks_counter++;
//--- We should periodically reset the counter ticks, to revive the distribution
if(ticks_counter>100)
{
Print("We've reset the indicator values, let's start filling the cells once again");
ticks_counter=0;
}
//--- Get a sample of random values as the sum of three numbers from 0 to 7
for(int i=0;i<sample_number;i++)
{
//--- Calculation of the index of the cell, where the random number falls as the sum of three
int rand_index=0;
//--- Get three random numbers from 0 to 7
for(int k=0;k<3;k++)
{
987
Math Functions
//--- A remainder in the division by 7 will return a value from 0 to 6
rand_index+=MathRand()%7;
}
//--- Increase the value in the cell number rand_index by 1
LabelBuffer[rand_index]++;
}
//--- Exit the OnCalculate() handler
return(rates_total);
}
988
Math Functions
MathTan
The function returns a tangent of a number.
double MathTan(
double rad
// argument in radians
);
Parameters
rad
[in] Angle in radians.
Return Value
Tangent of rad. If rad is greater than or equal to 263, or less than or equal to -263, a loss of
significance in the result occurs, in which case the function returns an indefinite number.
Note
Instead of MathTan() you can use tan().
See also
Real types (double, float)
989
Math Functions
MathIsValidNumber
It checks the correctness of a real number.
bool MathIsValidNumber(
double number
// number to check
);
Parameters
number
[in] Checked numeric value.
Return Value
It returns true, if the checked value is an acceptable real number. If the checked value is a plus or
minus infinity, or "not a number" (NaN), the function returns false.
Example:
double abnormal=MathArcsin(2.0);
if(!MathIsValidNumber(abnormal)) Print("Attention! MathArcsin(2.0) = ",abnormal);
See also
Real types(double,float)
990
String Functions
String Functions
This is a group of functions intended for working with data of the string type.
Function
Action
StringAdd
StringBufferLen
StringCompare
StringConcatenate
StringFill
StringFind
StringGetCharacter
StringInit
StringLen
StringReplace
StringSetCharacter
StringSplit
StringSubstr
StringToLower
StringToUpper
StringTrimLeft
StringTrimRight
991
String Functions
StringAdd
The function adds a substring to the end of a string.
bool StringAdd(
string& string_var,
string
add_substring
);
Parameters
string_var
[in][out] String, to which another one is added.
add_substring
[in] String that is added to the end of a source string.
Return Value
In case of success returns true, otherwise false. In order to get an error code, the GetLastError()
function should be called.
Example:
void OnStart()
{
long length=1000000;
string a="a",b="b",c;
//--- first method
uint start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c = a + b' = ",(stop-start)," milliseconds, i = ",i);
//--- second method
start=GetTickCount();
for(i=0;i<length;i++)
{
StringAdd(a,b);
}
stop=GetTickCount();
Print("time for 'StringAdd(a,b)' = ",(stop-start)," milliseconds, i = ",i);
//--- third method
start=GetTickCount();
a="a"; // re-initialize variable a
for(i=0;i<length;i++)
992
String Functions
{
StringConcatenate(c,a,b);
}
stop=GetTickCount();
Print("time for 'StringConcatenate(c,a,b)' = ",(stop-start)," milliseconds, i = ",i);
}
See also
StringConcatenate
993
String Functions
StringBufferLen
The function returns the size of buffer allocated 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
Minimal buffer size is equal to 16.
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
994
String Functions
StringCompare
The function compares two strings and returns the comparison result in form of an integer.
int StringCompare(
const string& string1,
bool
case_sensitive=true
);
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";
//--- compare case sensitive
int result1=StringCompare(s1,s2);
if(result1>0) PrintFormat("Case sensitive comparison: %s > %s",s1,s2);
else
{
if(result1<0)PrintFormat("Case sensitive comparison: %s < %s",s1,s2);
else PrintFormat("Case sensitive comparison: %s = %s",s1,s2);
}
//--- compare case-insensitive
int result2=StringCompare(s1,s2,false);
if(result2>0) PrintFormat("Case insensitive comparison: %s > %s",s1,s2);
else
995
String Functions
{
if(result2<0)PrintFormat("Case insensitive comparison: %s < %s",s1,s2);
else PrintFormat("Case insensitive comparison: %s = %s",s1,s2);
}
/* Result:
Case-sensitive comparison: Apple < home
Case insensitive comparison: Apple < home
*/
}
See also
String Type, CharToString(), ShortToString(), StringToCharArray(), StringToShortArray(),
StringGetCharacter(), Use of a Codepage
996
String Functions
StringConcatenate
The function forms a string of passed parameters and returns the size of the formed string.
Parameters can be of any type. Number of parameters can't be less than 2 or more than 64.
int StringConcatenate(
string& string_var,
// string to form
void argument1
void argument2
...
);
Parameters
string_var
[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 same rules as in Print() and Comment().
See also
StringAdd
997
String Functions
StringFill
It fills out a selected string by specified symbols.
bool StringFill(
string&
string_var,
// string to fill
ushort
character
);
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
998
String Functions
StringFind
Search for a substring in a string.
int StringFind(
string string_value,
string match_substring,
// what is searched
int
start_pos=0
);
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.
999
String Functions
StringGetCharacter
Returns value of a symbol, located in the specified position of a string.
ushort StringGetCharacter(
string string_value,
// string
int
pos
);
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().
1000
String Functions
StringInit
Initializes a string by specified symbols and provides the specified string size.
bool StringInit(
string&
string_var,
// string to initialize
int
new_len=0,
ushort
character=0
);
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
StringLen(str) = 0
*/
See also
StringBufferLen, StringLen
1001
String Functions
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
Number of symbols in a string without the ending zero.
1002
String Functions
StringReplace
It replaces all the found substrings of a string by a set sequence of symbols.
int StringReplace(
string&
str,
const string
find,
const string
replacement
);
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()
1003
String Functions
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 string remains unchanged). The string length becomes equal to pos.
If pos is equal to string length, the specified symbol is added at the string end, and the length is
enlarged by one.
Example:
void OnStart()
{
string str="0123456789";
Print("before: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str),"
StringLen(str) = ",StringLen(str));
StringLen(str) = ",StringLen(str));
StringLen(str) = ",StringLen(str));
}
/* Result
before: str = 0123456789 ,StringBufferLen(str) = 0
after: str = 012345 ,StringBufferLen(str) = 16
StringLen(str) = 10
StringLen(str) = 6
StringLen(str) = 7
*/
1004
String Functions
See also
StringBufferLen, StringLen, StringFill, StringInit
1005
String Functions
StringSplit
Gets substrings by a specified separator from the specified string, returns the number of substrings
obtained.
int StringSplit(
const string string_value,
// A string to search in
const ushort
separator,
string
& result[]
);
Parameters
string_value
[in] The string from which you need to get substrings. The string will not change.
pos
[in] The code of the separator character. To get the code, you can use the StringGetCharacter()
function.
result[]
[out] An array of strings where the obtained substrings are located.
Return Value
The number of substrings in the result[] array. If the separator is not found in the passed string,
only one source string will be placed in the array.
If string_value is empty or NULL, the function will return zero. In case of an error the function
returns -1. To get the error code, call the GetLastError() function.
Example:
string to_split="_life_is_good_"; // A string to split into substrings
string sep="_";
// A separator as a character
ushort u_sep;
string result[];
1006
String Functions
See also
StringReplace(), StringSubstr(), StringConcatenate()
1007
String Functions
StringSubstr
Extracts a substring from a text string starting from the specified position.
string StringSubstr(
string string_value,
// string
int
start_pos,
int
length=-1
);
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
Copy of a extracted substring, if possible. Otherwise returns an empty string.
1008
String Functions
StringToLower
Transforms all symbols of a selected string into lowercase.
bool StringToLower(
string& string_var
// string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
1009
String Functions
StringToUpper
Transforms all symbols of a selected string into capitals.
bool StringToUpper(
string& string_var
// string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code call GetLastError().
1010
String Functions
StringTrimLeft
The function cuts line feed characters, spaces and tabs in the left part of the string till the first
meaningful symbol. The string is modified at place.
int StringTrimLeft(
string& string_var
// string to cut
);
Parameters
string_var
[in][out] String that will be cut from the left.
Return Value
Returns the number of cut symbols.
1011
String Functions
StringTrimRight
The function cuts line feed characters, spaces and tabs in the right part of the string after the last
meaningful symbol. The string is modified at place.
int StringTrimRight(
string& string_var
// string to cut
);
);
Parameters
string_var
[in][out] String that will be cut from the right.
Return Value
Returns the number of cut symbols.
1012
Action
TimeCurrent
TimeTradeServer
TimeLocal
TimeGMT
TimeDaylightSavings
TimeGMTOffset
TimeToStruct
StructToTime
1013
TimeCurrent
Returns the last known server time, time of the last quote receipt for one of the symbols selected in
the "Market Watch" window. In the OnTick() handler, this function returns the time of the received
handled tick. In other cases (for example, call in handlers OnInit(), OnDeinit(), OnTimer() and so on)
this is the time of the last quote receipt for any symbol available in the "Market Watch" window, the
time shown in the title of this window. The time value is formed on a trade server and does not
depend on the time settings on your computer. There are 2 variants of the function.
Call without parameters
datetime TimeCurrent();
);
Parameters
dt_struct
[out] MqlDateTime structure type variable.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeCurrent() is simulated according to historical data.
1014
TimeTradeServer
Returns the calculated current time of the trade server. Unlike TimeCurrent(), the calculation of the
time value is performed in the client terminal and depends on the time settings on your computer.
There are 2 variants of the function.
Call without parameters
datetime TimeTradeServer();
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeTradeServer() is simulated according to historical data
and always equal to TimeCurrent().
1015
TimeLocal
Returns the local time of a computer, where the client terminal is running. There are 2 variants of the
function.
Call without parameters
datetime TimeLocal();
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeLocal() is always equal to TimeCurrent() simulated server
time.
1016
TimeGMT
Returns the GMT, which is calculated taking into account the DST switch by the local time on the
computer where the client terminal is running. There are 2 variants of the function.
Call without parameters
datetime TimeGMT();
);
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeGMT() is always equal to TimeTradeServer() simulated
server time.
1017
TimeDaylightSavings
Returns correction for daylight saving time in seconds, if the switch to summer time has been made.
It depends on the time settings of your computer.
int TimeDaylightSavings();
Return Value
If switch to winter (standard) time has been made, it returns 0.
1018
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.
1019
TimeToStruct
Converts a value of datetime type (number of seconds since 01.01.1970) into a structure variable
MqlDateTime.
void TimeToStruct(
datetime
dt,
MqlDateTime& dt_struct
);
Parameters
dt
[in] Date value to convert.
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
No return value.
1020
StructToTime
Converts a structure variable MqlDateTime into a value of datetime type and returns the resulting
value.
datetime StructToTime(
MqlDateTime$ dt_struct
);
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.
1021
Account Information
Account Information
Functions that return parameters of the current account.
Function
Action
AccountInfoDouble
AccountInfoInteger
AccountInfoString
type
of
the
1022
Account Information
AccountInfoDouble
Returns the value of the corresponding account property.
double AccountInfoDouble(
int property_id
);
Parameters
property_id
[in]
Identifier of the property.
ENUM_ACCOUNT_INFO_DOUBLE.
The
value
can
be
one
of
the
values
Return Value
Value of double type.
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoDouble()
printf("ACCOUNT_BALANCE =
%G",AccountInfoDouble(ACCOUNT_BALANCE));
printf("ACCOUNT_CREDIT =
%G",AccountInfoDouble(ACCOUNT_CREDIT));
printf("ACCOUNT_PROFIT =
%G",AccountInfoDouble(ACCOUNT_PROFIT));
printf("ACCOUNT_EQUITY =
%G",AccountInfoDouble(ACCOUNT_EQUITY));
printf("ACCOUNT_MARGIN =
%G",AccountInfoDouble(ACCOUNT_MARGIN));
printf("ACCOUNT_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
of
1023
Account Information
AccountInfoInteger
Returns the value of the properties of the account.
long AccountInfoInteger(
int property_id
);
Parameters
property_id
[in]
Identifier of the property.
ENUM_ACCOUNT_INFO_INTEGER.
The
value
can
be
one
of
the
values
of
Return Value
Value of long type.
Note
The property must be one of the bool, int or long types.
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoInteger()
printf("ACCOUNT_LOGIN =
%d",AccountInfoInteger(ACCOUNT_LOGIN));
printf("ACCOUNT_LEVERAGE =
%d",AccountInfoInteger(ACCOUNT_LEVERAGE));
bool thisAccountTradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_ALLOWED);
bool EATradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_EXPERT);
ENUM_ACCOUNT_TRADE_MODE tradeMode=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_MODE
ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=(ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoInteger(ACCOUNT_MARG
//--- Inform about the possibility to perform a trade operation
if(thisAccountTradeAllowed)
Print("Trade for this account is permitted");
else
Print("Trade for this account is prohibited!");
//--- Find out if it is possible to trade on this account by Expert Advisors
if(EATradeAllowed)
Print("Trade by Expert Advisors is permitted for this account");
else
Print("Trade by Expert Advisors is prohibited for this account!");
//--- Find out the account type
switch(tradeMode)
{
case(ACCOUNT_TRADE_MODE_DEMO):
Print("This is a demo account");
break;
1024
Account Information
case(ACCOUNT_TRADE_MODE_CONTEST):
Print("This is a competition account");
break;
default:Print("This is a real account!");
}
//--- Find out the StopOut level setting mode
switch(stopOutMode)
{
case(ACCOUNT_STOPOUT_MODE_PERCENT):
Print("The StopOut level is specified percentage");
break;
default:Print("The StopOut level is specified in monetary terms");
}
}
See also
Account Information
1025
Account Information
AccountInfoString
Returns the value of the corresponding account property.
string AccountInfoString(
int property_id
);
Parameters
property_id
[in]
Identifier of the property.
ENUM_ACCOUNT_INFO_STRING.
The
value
can
be
one
of
the
values
Return Value
Value of string type.
Example:
void OnStart()
{
//--- Show all the information available from the function AccountInfoString()
Print("The name of the broker = ",AccountInfoString(ACCOUNT_COMPANY));
Print("Deposit currency = ",AccountInfoString(ACCOUNT_CURRENCY));
Print("Client name = ",AccountInfoString(ACCOUNT_NAME));
Print("The name of the trade server = ",AccountInfoString(ACCOUNT_SERVER));
}
See also
Account Information
of
1026
Checkup
State Checking
Functions that return parameters of the current state of the client terminal
Function
Action
GetLastError
IsStopped
UninitializeReason
TerminalInfoInteger
TerminalInfoDouble
TerminalInfoString
MQLInfoInteger
MQLInfoString
Symbol
Period
Digits
Point
of
the
reason
for
1027
Checkup
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().
See also
Trade Server Return Codes
1028
Checkup
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.
1029
Checkup
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.
1030
Checkup
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 of the values of the ENUM_TERMINAL_INFO_INTEGER
enumeration.
Return Value
Value of int type.
1031
Checkup
TerminalInfoDouble
Returns the value of a corresponding property of the mql5 program environment.
double TerminalInfoDouble(
int property_id
// identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the values of the ENUM_TERMINAL_INFO_DOUBLE
enumeration.
Return Value
Value of double type.
1032
Checkup
TerminalInfoString
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. Can be one of the values of the ENUM_TERMINAL_INFO_STRING
enumeration.
Return Value
Value of string type.
1033
Checkup
MQLInfoInteger
Returns the value of a corresponding property of a running mql5 program.
int MQLInfoInteger(
int property_id
// identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of values of the ENUM_MQL_INFO_INTEGER enumeration.
Return Value
Value of int type.
1034
Checkup
MQLInfoString
Returns the value of a corresponding property of a running mql5 program.
string MQLInfoString(
int property_id
// Identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the ENUM_MQL_INFO_STRING enumeration.
Return Value
Value of string type.
1035
Checkup
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.
1036
Checkup
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
PeriodSeconds, Chart timeframes, Date and Time, Visibility of objects
1037
Checkup
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.
1038
Checkup
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.
1039
Market Info
Action
SymbolsTotal
SymbolName
SymbolSelect
SymbolIsSynchronized
SymbolInfoDouble
SymbolInfoInteger
SymbolInfoString
SymbolInfoMarginRate
SymbolInfoTick
SymbolInfoSessionQuote
SymbolInfoSessionTrade
MarketBookAdd
MarketBookRelease
MarketBookGet
1040
Market Info
SymbolsTotal
Returns the number of available (selected in Market Watch or all) symbols.
int SymbolsTotal(
bool selected
);
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.
1041
Market Info
SymbolName
Returns the name of a symbol.
string SymbolName(
int
pos,
bool selected
);
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
Value of string type with the symbol name.
1042
Market Info
SymbolSelect
Selects a symbol in the Market Watch window or removes a symbol from the window.
bool SymbolSelect(
string name,
// symbol name
bool
// add or remove
select
);
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
In case of failure returns false.
1043
Market Info
SymbolIsSynchronized
The function checks whether data of a selected symbol in the terminal are synchronized with data on
the trade server.
bool SymbolIsSynchronized(
string name,
// symbol name
);
Parameters
name
[in] Symbol name.
Return value
If data are synchronized, returns 'true'; otherwise returns 'false'.
See also
SymbolInfoInteger, Organizing Data Access
1044
Market Info
SymbolInfoDouble
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
1. Immediately returns the property value.
double SymbolInfoDouble(
string
name,
ENUM_SYMBOL_INFO_DOUBLE prop_id
// symbol
// 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
ENUM_SYMBOL_INFO_DOUBLE
prop_id,
double&
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values
ENUM_SYMBOL_INFO_DOUBLE enumeration.
of the
double_var
[out] Variable of double type receiving the value of the requested property.
Return Value
The value of double type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
5040 invalid string parameter for specifying a symbol name,
4301 unknown symbol (financial instrument),
4302 symbol is not selected in "Market Watch" (not found in the list of available ones),
4303 invalid identifier of a symbol property.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive the values of
Ask, Bid, Last, Volume and the time of the last tick's arrival during a single call.
Example:
void OnTick()
1045
Market Info
{
//--- 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);
}
1046
Market Info
SymbolInfoInteger
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
1. Immediately returns the property value.
long SymbolInfoInteger(
string
name,
// symbol
ENUM_SYMBOL_INFO_INTEGER
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
ENUM_SYMBOL_INFO_INTEGER
prop_id,
// identifier of a property
long&
long_var
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values
ENUM_SYMBOL_INFO_INTEGER enumeration.
of the
long_var
[out] Variable of the long type receiving the value of the requested property.
Return Value
The value of long type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
5040 invalid string parameter for specifying a symbol name,
4301 unknown symbol (financial instrument),
4302 symbol is not selected in "Market Watch" (not found in the list of available ones),
4303 invalid identifier of a symbol property.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive the values of
Ask, Bid, Last, Volume and the time of the last tick's arrival during a single call.
Example:
1047
Market Info
void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}
1048
Market Info
SymbolInfoString
Returns the corresponding property of a specified symbol. There are 2 variants of the function.
1. Immediately returns the property value.
string SymbolInfoString(
string
name,
ENUM_SYMBOL_INFO_STRING prop_id
// Symbol
// 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 placeholder variable passed by reference in the last parameter.
bool SymbolInfoString(
string
name,
// Symbol
ENUM_SYMBOL_INFO_STRING
prop_id,
// Property identifier
string&
string_var
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values
ENUM_SYMBOL_INFO_STRING enumeration.
of the
string_var
[out] Variable of the string type receiving the value of the requested property.
Return Value
The value of string type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
5040 invalid string parameter for specifying a symbol name,
4301 unknown symbol (financial instrument),
4302 symbol is not selected in "Market Watch" (not found in the list of available ones),
4303 invalid identifier of a symbol property.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive the values of
Ask, Bid, Last, Volume and the time of the last tick's arrival during a single call.
1049
Market Info
SymbolInfoMarginRate
Returns the margin rates depending on the order type and direction.
bool SymbolInfoMarginRate(
string
name,
// symbol name
ENUM_ORDER_TYPE
order_type,
// order type
double&
initial_margin_rate,
double&
maintenance_margin_rate
);
Parameters
name
[in] Symbol name.
order_type
[in] Order type.
initial_margin_rate
[in] A double type variable for receiving an initial margin rate. Initial margin is a security deposit
for 1 lot deal in the appropriate direction. Multiplying the rate by the initial margin, we receive the
amount of funds to be reserved on the account when placing an order of the specified type.
maintenance_margin_rate
[out] A double type variable for receiving a maintenance margin rate. Maintenance margin is a
minimum amount for maintaining an open position of 1 lot in the appropriate direction. Multiplying
the rate by the maintenance margin, we receive the amount of funds to be reserved on the
account after an order of the specified type is activated.
Return Value
Returns true if request for properties is successful, otherwise false.
1050
Market Info
SymbolInfoTick
The function returns current prices of a specified symbol in a variable of the MqlTick type.
bool SymbolInfoTick(
string
symbol,
MqlTick& tick
// symbol name
// reference to a structure
);
Parameters
symbol
[in] Symbol name.
tick
[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
The function returns true if successful, otherwise returns false.
1051
Market Info
SymbolInfoSessionQuote
Allows receiving time of beginning and end of the specified quoting sessions for a specified symbol
and day of week.
bool SymbolInfoSessionQuote(
string
name,
// symbol name
ENUM_DAY_OF_WEEK day_of_week,
uint
session_index,
// session index
datetime&
from,
datetime&
to
);
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
1052
Market Info
SymbolInfoSessionTrade
Allows receiving time of beginning and end of the specified trading sessions for a specified symbol and
day of week.
bool SymbolInfoSessionTrade(
string
name,
// symbol name
ENUM_DAY_OF_WEEK day_of_week,
uint
session_index,
// session index
datetime&
from,
datetime&
to
);
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
1053
Market Info
MarketBookAdd
Provides opening of Depth of Market for a selected symbol, and subscribes for receiving notifications
of the DOM changes.
bool MarketBookAdd(
string symbol
// symbol
);
Parameters
symbol
[in] The name of a symbol, whose Depth of Market is to be used in the Expert Advisor or script.
Return Value
The true value if opened successfully, otherwise false.
Note
Normally, this function must be called from the OnInit() function or in the class constructor. To
handle incoming alerts, in the Expert Advisor program must contain the function void
OnBookEvent(string& symbol).
See also
Structure of Depth of Market, Structures and Classes
1054
Market Info
MarketBookRelease
Provides closing of Depth of Market for a selected symbol, and cancels the subscription for receiving
notifications of the DOM changes.
bool MarketBookRelease(
string symbol
// symbol
);
Parameters
symbol
[in] Symbol name.
Return Value
The true value if closed successfully, otherwise false.
Note
Normally, this function must be called from the OnDeinit() function, if the corresponding
MarketBookAdd() function has been called in the OnInit() function. Or it must be called from the
class destructor, if the corresponding MarketBookAdd() function has been called from the class
constructor.
See also
Structure of Depth of Market, Structures and Classes
1055
Market Info
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
Returns true in case of success, otherwise false.
Note
The Depth of Market must be pre-opened by the MarketBookAdd() function.
Example:
MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo for ",Symbol());
for(int i=0;i<size;i++)
{
Print(i+":",priceArray[i].price
+"
Volume = "+priceArray[i].volume,
See also
Structure of Depth of Market, Structures and Classes
1056
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
1057
Action
SeriesInfoInteger
Returns information
historical data
Bars
BarsCalculated
IndicatorCreate
IndicatorParameters
IndicatorRelease
CopyBuffer
CopyRates
CopyTime
CopyOpen
CopyHigh
CopyLow
CopyClose
CopyTickVolume
CopyRealVolume
CopySpread
about
the
state
of
1058
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]);
}
1059
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
1060
1061
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:
int copied=CopyBuffer(ma_handle,// Indicator handle
0,
0,
number,
Buffer
1062
Example:
input int per=10; // period of the exponent
int ma_handle;
// indicator handle
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--ma_handle=iMA(_Symbol,0,per,0,MODE_EMA,PRICE_CLOSE);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
//--double ema[10];
int copied=CopyBuffer(ma_handle,// indicator handle
0,
0,
10,
ema
);
if(copied<0) return;
// .... further code
}
See also
Organizing Data Access
1063
1064
Data Availability
Presence of data on HCC format or even in the prepared for using HC format does not always denote
the absolute availability of these data to be shown in a chart or to be used in MQL5 programs.
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
database is given.
The price history for all timeframes is built from common data of HCC format, and any update of data
from a server leads to the update of data for all timeframes and to the recalculation of indicators. Due
to this access to data can be closed, even if these data were available a moment ago.
1065
The CheckLoadHistory() function is designed as a universal function that can be called from any
program (Expert Advisor, script or indicator); and therefore it requires three input parameters: symbol
name, period and start date to indicate the beginning of price history you need.
Insert necessary checks into the function code before requesting the missing history. First of all, we
should make sure that the symbol name and period value are correct:
if(symbol==NULL || symbol=="") symbol=Symbol();
if(period==PERIOD_CURRENT)
period=Period();
Then let's make sure that the symbol is available in the 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))
{f
if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1);
SymbolSelect(symbol,true);
}
Now we should receive the start date of the available history for the indicated symbol/period pair.
Perhaps, the value of the input parameter startdate, passed to CheckLoadHistory(), is within the
available history; then request to a trade server is not needed. In order to obtain the very first date
for the symbol-period as of the moment, the 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
that it is not desirable to send a request to update the timeseries from indicator with the same
period. The undesirability of requesting data on the same symbol-period as that of the indicator is
conditioned by the fact that update of history data is performed in the same thread where the
indicator operates. So the possibility of deadlock 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 do 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
1066
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;
Since the request is an asynchronous operation, the function is called in the loop with a small delay of
5 milliseconds until the first_server_date variable receives a value, or the loop execution is
terminated by a user (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 loop and start filling out its body:
while(!IsStopped())
{
//1. wait for synchronization between the re-built timeseries and intermediate history as HHC
//2. receive the current number of bars in this timeseries
//
//3. obtain the start date first_date in the re-built timeseries and compare it to start_date
//
//4. request from a server a new part of history - 100 bars starting from last available bar
}
1067
The last fourth point is left - requesting history. We can't refer to a server directly, but any Copyfunction 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 copied) must always be within the
available terminal history. If you have only 100 bars, it meaningless to try copying 300 bars starting
from the bar with the index 500. 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 bars in groups of 100 starting from the bar with the bars index. This will provide
the smooth loading of missing history from a trade server. Actually a little more than the requested
100 bars will be loaded, while server sends oversized history.
int copied=CopyTime(symbol,period,bars,100,times);
After the copying operation, we should analyze the number of copied elements. If the attempt fails,
then value of the copied will be equal to null and the value of the fail_cnt counter will be increased by
1. After 100 failing attempts, the operation of the function will be stopped.
int fail_cnt=0;
...
int copied=CopyTime(symbol,period,bars,100,times);
if(copied>0)
{
//--- check data
if(times[0]<=start_date)
return(0);
if(bars+copied>=max_bars) return(-2); // bars are more than can be drawn in the chart, ready
fail_cnt=0;
}
else
1068
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;
break;
break;
case
break;
case
break;
case
break;
The full code of the function can be found in the example of a script that shows the correct
organization of access to any data with the handling of request's results.
Code:
//+------------------------------------------------------------------+
//|
TestLoadHistory.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.02"
#property script_show_inputs
//--- input parameters
input string
InpLoadedSymbol="NZDUSD";
// Symbol to be load
// Period to be loaded
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
Print("Start load",InpLoadedSymbol+","+GetPeriodName(InpLoadedPeriod),"from",InpStartDate);
//---
1069
break;
break;
break;
break;
case
0 : Print("Loaded OK");
break;
case
1 : Print("Loaded previously");
break;
case
break;
//+------------------------------------------------------------------+
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();
1070
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);
}
1071
//+------------------------------------------------------------------+
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");
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");
return("Daily");
case PERIOD_W1:
return("Weekly");
1072
SeriesInfoInteger
Returns information about the state of historical data. There are 2 variants of function calls.
Directly returns the property value.
long SeriesInfoInteger(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES
timeframe,
// period
ENUM_SERIES_INFO_INTEGER
prop_id,
// property identifier
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES
timeframe,
// period
ENUM_SERIES_INFO_INTEGER
prop_id,
// property ID
long&
long_var
);
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
In the first case, it returns value of the long type.
For the second case, it returns true, if the specified property is available and its value has been
placed into long_var variable, otherwise it returns false. For more details about an error, call
GetLastError().
Example:
void OnStart()
{
//--Print("Total number of bars for the symbol-period at this moment = ",
SeriesInfoInteger(Symbol(),0,SERIES_BARS_COUNT));
Print("The first date for the symbol-period at this moment = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_FIRSTDATE));
1073
Print("The first date in the history for the symbol-period on the server = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE));
Print("Symbol data are synchronized = ",
(bool)SeriesInfoInteger(Symbol(),0,SERIES_SYNCHRONIZED));
}
1074
Bars
Returns the number of bars count in the history for a specified symbol and period. There are 2
variants of functions calls.
Request all of the history bars
int Bars(
string
symbol_name,
ENUM_TIMEFRAMES timeframe
// symbol name
// period
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_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
1075
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 Handling Functions
1076
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 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;
}
1077
copied = ",copied);
}
else Print("Upper fractals copied. ArraySize = ",ArraySize(Ups));
}
1078
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_type,
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_type
[in] Indicator type, can be one of values of the ENUM_INDICATOR enumeration.
parameters_cnt
[in] The number of parameters passed in the parameters_array[] array. The array elements have a
special structure type 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.
Return 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.
Indicators that require testing are defined automatically from the call of the iCustom() function, if
the corresponding parameter is set through a constant string. For all other cases (use of the
IndicatorCreate() function or use of a non-constant string in the parameter that sets the indicator
name) the property #property tester_indicator is required:
#property tester_indicator "indicator_name.ex5"
1079
h_MA,h_MACD;
=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);
}
1080
IndicatorParameters
Based on the specified handle, returns the number of input parameters of the indicator, as well as the
values and types of the parameters.
int IndicatorParameters(
int
indicator_handle,
// indicator handle
ENUM_INDICATOR& indicator_type,
MqlParam&
parameters[]
);
Parameters
indicator_handle
[in] The handle of the indicator, for which you need to know the number of parameters its is
calculated on.
indicator_type
[out] A variable if the ENUM_INDICATOR type, into which the indicator type will be written.
parameters[]
[out] A dynamic array for receiving values of the MqlParam type, into which the list of indicator
parameters will be written. The array size is returned by the IndicatorParameters() function.
Return Value
The number of input parameters of the indicator with the specified handle. In case of an error
returns -1. For more details about the error call the GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- The number of windows on the chart (at least one main window is always present)
int windows=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
//--- Go through the chart windows
for(int w=0;w<windows;w++)
{
//--- The number of indicators in this window/subwindow
int total=ChartIndicatorsTotal(0,w);
//--- Take all indicators in the window
for(int i=0;i<total;i++)
{
//--- Get the short name of the indicator
string name=ChartIndicatorName(0,w,i);
//--- Get the indicator handle
int handle=ChartIndicatorGet(0,w,name);
//--- Add to log
1081
indicator #%d,
handle=%d",w,i,handle);
//--MqlParam parameters[];
ENUM_INDICATOR indicator_type;
int params=IndicatorParameters(handle,indicator_type,parameters);
//--- The header of the message
string par_info="Short name "+name+", type "
+EnumToString(ENUM_INDICATOR(indicator_type))+"\r\n";
//--for(int p=0;p<params;p++)
{
See also
ChartIndicatorGet()
1082
IndicatorRelease
The function removes an indicator handle and releases the calculation block of the indicator, if it's not
used by anyone else.
bool IndicatorRelease(
int
indicator_handle
// indicator handle
);
Return Value
Returns true in case of success, otherwise returns false.
Note
The function allows removing an indicator handle, if it's no longer needed, thus saving memory. The
handle is removed immediately, the calculation block is deleted in some time (if it's not called
anymore).
Example:
//+------------------------------------------------------------------+
//|
Test_IndicatorRelease.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
MA_Period=15;
input int
MA_shift=0;
input ENUM_MA_METHOD
MA_smooth=MODE_SMA;
//+------------------------------------------------------------------+
int OnInit()
{
//--- create indicator handle
MA_handle=iMA(Symbol(),0,MA_Period,MA_shift,MA_smooth,PRICE_CLOSE);
//--- delete global variable
if(GlobalVariableCheck("MA_value"))
GlobalVariableDel("MA_value");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function
1083
1084
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 of a receiving array
from this intermediate one.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false. Data will be
copied so that the oldest element will be located at the start of the physical memory allocated for the
array. There are 3 variants of function calls.
Call by the first position and the number of required elements
int CopyBuffer(
int
indicator_handle,
// indicator handle
int
buffer_num,
int
start_pos,
// start position
int
count,
// amount to copy
double
buffer[]
);
indicator_handle,
// indicator handle
1085
buffer_num,
datetime start_time,
int
count,
// amount to copy
double
buffer[]
);
indicator_handle,
// indicator handle
int
buffer_num,
datetime start_time,
datetime stop_time,
double
buffer[]
);
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
Returns the copied data count or -1 in case of an error.
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.
1086
TestCopyBuffer3.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
//---- plot MA
#property indicator_label1
"MA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
AsSeries=true;
input int
period=15;
input ENUM_MA_METHOD
smootMode=MODE_EMA;
shift=0;
MABuffer[];
int
ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("Parameter AsSeries = ",AsSeries);
Print("Indicator buffer after SetIndexBuffer() is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//--- set short indicator name
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//--- set AsSeries (depends on input parameter)
ArraySetAsSeries(MABuffer,AsSeries);
Print("Indicator buffer after ArraySetAsSeries(MABuffer,true); is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//--ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(INIT_SUCCEEDED);
}
1087
//+------------------------------------------------------------------+
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 a detailed example of history requesting data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
DRAW_COLOR_ARROW,
DRAW_COLOR_ZIGZAG.
See also
1088
1089
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.
Call by the first position and the number of required elements
int CopyRates(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
MqlRates
rates_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
MqlRates
rates_array[]
);
1090
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
MqlRates
rates_array[]
);
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
Returns the number of copied elements or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1091
See a detailed example of requesting history data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
1092
See also
Structures and Classes, TimeToString, StringFormat
1093
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.
Call by the first position and the number of required elements
int CopyTime(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
datetime
time_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
datetime
time_array[]
);
open times
1094
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
datetime
time_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1095
1096
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.
Call by the first position and the number of required elements
int CopyOpen(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
double
open_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
double
open_array[]
);
1097
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
double
open_array[]
);
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
Returns the number of element in the array or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1098
1099
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.
Call by the first position and the number of required elements
int CopyHigh(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
double
high_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
double
high_array[]
);
1100
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
double
high_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1101
"https://www.mql5.com"
#property version
"1.00"
#property description "An example for output of the High[i] and Low[i]"
#property description "for a random chosen bars"
double High[],Low[];
//+------------------------------------------------------------------+
//| Get Low for specified bar index
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double low=0;
ArraySetAsSeries(Low,true);
int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
if(copied>0 && index<copied) low=Low[index];
return(low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double high=0;
ArraySetAsSeries(High,true);
int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
if(copied>0 && index<copied) high=High[index];
return(high);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
1102
Low[%d] = %G",
sec,iHigh(Symbol(),0,sec),
sec,iLow(Symbol(),0,sec));
}
See a detailed example of requesting history data in the Methods of Object Binding section. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
DRAW_COLOR_ARROW,
DRAW_COLOR_ZIGZAG.
1103
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.
Call by the first position and the number of required elements
int CopyLow(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
double
low_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
double
low_array[]
);
1104
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
double
low_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1105
See also
CopyHigh
1106
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.
Call by the first position and the number of required elements
int CopyClose(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
double
close_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
double
close_array[]
);
1107
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
double
close_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1108
1109
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.
Call by the first position and the number of required elements
int CopyTickVolume(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
long
volume_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
long
volume_array[]
);
1110
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
long
volume_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1111
"TickVolume"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
C'143,188,139'
#property indicator_style1
STYLE_SOLID
#property indicator_width1
bars=3000;
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[],
1112
See a detailed example of history data requesting in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
DRAW_COLOR_ARROW,
DRAW_COLOR_ZIGZAG.
1113
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.
Call by the first position and the number of required elements
int CopyRealVolume(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
long
volume_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
long
volume_array[]
);
1114
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
long
volume_array[]
);
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
Returns the copied data count or -1 in the case of error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1115
1116
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.
Call by the first position and the number of required elements
int CopySpread(
string
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
int
start_pos,
// start position
int
count,
int
spread_array[]
);
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
int
count,
int
spread_array[]
);
1117
symbol_name,
// symbol name
ENUM_TIMEFRAMES timeframe,
// period
datetime
start_time,
datetime
stop_time,
int
spread_array[]
);
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
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_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 by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.
1118
"Spread"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
bars=3000;
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[],
1119
Bid = ",Bid);
SpreadBuffer[rates_total-1]=(Ask-Bid)/Point();
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See an example of history data requesting in section Methods of Object Binding. The script available
in that section shows how to get the values of indicator iFractals on the last 1000 bars and how to
display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
DRAW_COLOR_ARROW,
DRAW_COLOR_ZIGZAG.
1120
CopyTicks
The function receives ticks accumulated by the terminal for the current work session and writes them
into the ticks_array. It should be noted that the order of indexing goes from the past to the present,
that is tick index 0 is the oldest one in the array.
int CopyTicks(
string
symbol_name,
// symbol name
MqlTick&
ticks_array[],
uint
flags=COPY_TICKS_ALL, // the flag that defines the type of the ticks that are
ulong
from=0,
uint
count=0
);
Parameters
symbol_name
[in] Symbol.
ticks_array
[out] MqlTick type array for receiving ticks.
flags
[in] The flag to define the type of the ticks you want to receive. COPY_TICKS_INFO only Bid and
Ask, COPY_TICKS_TRADE only Last and Volume, COPY_TICKS_ALL all ticks.
from
[in] The first date of requested ticks. In milliseconds since 1970.01.01. If the parameter from=0
then last count tick will be written.
count
[in] The number of requested ticks. If the date and number are not specified, all available ticks
are received, but not more than 2000.
Return Value
The number of copied tick or -1 in case of an error.
Note
The OnTick() function does not handle every tick, it notifies the Expert Advisor of market changes.
It can be a batch of changes: the terminal can simultaneously make a few ticks, but OnTick() will be
called only once to notify the EA of the latest market state. The CopyTicks() function allows you to
request and analyze all the ticks.
If the from and count parameters are not specified, all available ticks, but no more than 2000, will
be written in the ticks_array[]. The flags parameter allows setting the type of required ticks.
Example:
//--- input parameters
input int
ticks=10;
//+------------------------------------------------------------------+
//| Expert tick function
1121
Time
Bid
Ask\r\n";
%G
%G",
i,
TimeToString(tick.time,TIME_MINUTES|TIME_SECONDS),
tick.bid,
tick.ask);
comment=comment+tick_string+"\r\n";
}
//--- show a comment on the chart
Comment(comment);
}
else // report an error that occurred when receiving ticks
{
Comment("Ticks could not be loaded. GetLastError()=",GetLastError());
}
}
See also
SymbolInfoTick, Structure for Current Prices, OnTick()
1122
Chart Operations
Chart Operations
These are functions for working with charts. All chart operations are allowed in Expert Advisors and
scripts only.
The functions defining the chart properties are actually used for sending change commands to the
chart. If these functions are executed successfully, the command is included in the common queue of
the chart events. The changes are implemented to the chart when handling the queue of the chart
events.
Thus, do not expect an immediate visual update of the chart after calling these functions. Generally,
the chart is updated automatically by the terminal following the change events - a new quote arrival,
resizing the chart window, etc. Use ChartRedraw() function to forcefully update the chart.
Function
Action
ChartApplyTemplate
ChartSaveTemplate
ChartWindowFind
ChartTimePriceToXY
ChartXYToTimePrice
ChartOpen
ChartClose
ChartFirst
ChartNext
ChartSymbol
ChartPeriod
ChartRedraw
ChartSetDouble
ChartSetInteger
ChartSetString
1123
Chart Operations
ChartGetInteger
ChartGetString
ChartNavigate
ChartID
ChartIndicatorAdd
ChartIndicatorDelete
ChartIndicatorGet
ChartIndicatorName
ChartIndicatorsTotal
ChartWindowOnDropped
ChartPriceOnDropped
ChartTimeOnDropped
ChartXOnDropped
ChartYOnDropped
ChartSetSymbolPeriod
ChartScreenShot
1124
Chart Operations
ChartApplyTemplate
Applies a specific template from a specified file to the chart. The command is added to chart
messages queue and will be executed after processing of all previous commands.
bool ChartApplyTemplate(
long
chart_id,
// Chart ID
// 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
Returns true if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note
The Expert Advisor will be unloaded and will not be able to continue operating in case of successful
loading of a new template to the chart it is attached to.
When applying the template to the chart, trade permissions may be limited due to security reasons:
Live trading permission cannot be extended for the Expert Advisors launched by
applying the template using ChartApplyTemplate() function.
If the mql5-program calling ChartApplyTemplate() function has no permission to trade, the Expert
Advisor launched via the template will also not be able to trade regardless of the template settings.
If the mql5-program calling ChartApplyTemplate() function has permission to trade, while there is no
such permission in the template settings, the Expert Advisor launched via the template will not be
able to trade.
Using Templates
The resources of the MQL5 language allow setting multiple chart properties, including colors using the
ChartSetInteger() function:
Chart background color;
Color of the axes, scale and the OHLC line;
Grid color;
Color of volumes and position open levels;
Color of the up bar, shadow and edge of a bullish candlestick;
Color of the down bar, shadow and edge of a bearish candlestick;
Color of the chart line and Doji candlesticks;
1125
Chart Operations
Color of the bullish candlestick body;
Color of the bearish candlestick body;
Color of the Bid price line;
Color of the Ask price line;
Color of the line of the last deal price (Last);
Color of the stop order levels (Stop Loss and Take Profit).
Besides, there can be multiple graphical objects and indicators on a chart. You may set up a chart with
all the necessary indicators once and then save it as a template. 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
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:
//--- search for a template in terminal_data_directory\MQL5\
ChartApplyTemplate(0,"\\first_template.tpl"))
Templates are not resources, they cannot be included into an executable EX5 file.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
1126
Chart Operations
void OnStart()
{
//--- example of applying template, located in \MQL5\Files
if(FileIsExist("my_template.tpl"))
{
Print("The file my_template.tpl found in \Files'");
//--- apply template
if(ChartApplyTemplate(0,"\\Files\\my_template.tpl"))
{
Print("The template 'my_template.tpl' applied successfully");
//--- redraw chart
ChartRedraw();
}
else
Print("Failed to apply 'my_template.tpl', error code ",GetLastError());
}
else
{
Print("File 'my_template.tpl' not found in "
+TerminalInfoString(TERMINAL_PATH)+"\\MQL5\\Files");
}
}
See also
Resources
1127
Chart Operations
ChartSaveTemplate
Saves current chart settings in a template with a specified name.
bool ChartSaveTemplate(
long
chart_id,
// Chart ID
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] The filename to save the template. The ".tpl" extension will be added to the filename
automatically; there is no need to specify it. The template is saved in terminal_directory\Profiles
\Templates\ and can be used for manual application in the terminal. If a template with the same
filename already exists, the contents of this file will be overwritten.
Return Value
If successful, the function returns true, otherwise it returns false. To get information about the
error, call the GetLastError() function.
Note
Using templates, you can save chart settings with all applied indicators and graphical objects, to
then apply it to another chart.
Example:
//+------------------------------------------------------------------+
//|
Test_ChartSaveTemplate.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property script_show_inputs
//--- input parameters
input string
symbol="GBPUSD";
input ENUM_TIMEFRAMES
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- First attach indicators to the chart
int handle;
//--- Prepare the indicator for use
1128
Chart Operations
if(!PrepareZigzag(NULL,0,handle)) return; // Failed, so exit
//--- Attach the indicator to the current chart, but in a separate window.
if(!ChartIndicatorAdd(0,1,handle))
{
PrintFormat("Failed to attach to chart %s/%s an indicator with the handle=%d. Error code %d",
_Symbol,
EnumToString(_Period),
handle,
GetLastError());
//--- Terminate the program operation
return;
}
//--- Refresh the chart to see the indicator
ChartRedraw();
//--- Find the last two last fractures of the zigzag
double two_values[];
datetime two_times[];
if(!GetLastTwoFractures(two_values,two_times,handle))
{
PrintFormat("Failed to find two last fractures in the Zigzag!");
//--- Terminate the program operation
return;
}
//--- Now attach a standard deviation channel
string channel="StdDeviation Channel";
if(!ObjectCreate(0,channel,OBJ_STDDEVCHANNEL,0,two_times[1],0))
{
PrintFormat("Failed to create object %s. Error code %d",
EnumToString(OBJ_STDDEVCHANNEL),GetLastError());
return;
}
else
{
//--- The channel has been created, define the second point
ObjectSetInteger(0,channel,OBJPROP_TIME,1,two_times[0]);
//--- Set a tooltip text for the channel
ObjectSetString(0,channel,OBJPROP_TOOLTIP,"Demo from MQL5 Help");
//--- Refresh the chart
ChartRedraw();
}
//--- Save the result in a template
ChartSaveTemplate(0,"StdDevChannelOnZigzag");
//--- Open a new chart and apply a saved template to it
long new_chart=ChartOpen(symbol,period);
//--- Enable tooltips for graphical objects
ChartSetInteger(new_chart,CHART_SHOW_OBJECT_DESCR,true);
if(new_chart!=0)
{
//--- Apply the saved template to a chart
1129
Chart Operations
ChartApplyTemplate(new_chart,"StdDevChannelOnZigzag");
}
Sleep(10000);
}
//+------------------------------------------------------------------+
//| Creates a zigzag handle and ensures readiness of its data
//+------------------------------------------------------------------+
bool PrepareZigzag(string sym,ENUM_TIMEFRAMES tf,int &h)
{
ResetLastError();
//--- The Zigzag indicator must be located in terminal_data_folder\MQL5\Examples
h=iCustom(sym,tf,"Examples\\Zigzag");
if(h==INVALID_HANDLE)
{
PrintFormat("%s: Failed to create the handle of the Zigzag indicator. Error code %d",
__FUNCTION__,GetLastError());
return false;
}
//--- When creating an indicator handle, it requires time to calculate values
int k=0; // The number of attempts to wait for the indicator calculation
//--- Wait for the calculation in a loop, pausing to 50 milliseconds if the calculation is not yet
while(BarsCalculated(h)<=0)
{
k++;
//--- Show the number of attempts
PrintFormat("%s: k=%d",__FUNCTION__,k);
//--- Wait 50 milliseconds to wait until the indicator is calculated
Sleep(50);
//--- If more than 100 attempt, then something is wrong
if(k>100)
{
//--- Report a problem
PrintFormat("Failed to calculate the indicator for %d attempts!");
//--- Terminate the program operation
return false;
}
}
//--- Everything is ready, the indicator is created and values are calculated
return true;
}
//+------------------------------------------------------------------+
//| Searches for the last 2 zigzag fractures and places to arrays
//+------------------------------------------------------------------+
bool GetLastTwoFractures(double &get_values[],datetime &get_times[],int handle)
{
double values[];
datetime times[];
int size=100;
ResetLastError();
1130
Chart Operations
//--- Copy the last 100 values of the indicator
int copied=CopyBuffer(handle,0,0,size,values);
//--- Check the number of values copied
if(copied<100)
{
PrintFormat("%s: Failed to copy %d values of the indicator with the handle=%d. Error code %d"
__FUNCTION__,size,handle,GetLastError());
return false;
}
//--- Define the order of access to the array as in a timeseries
ArraySetAsSeries(values,true);
//--- Write here the numbers of bars, in which fractures were found
int positions[];
//--- Set array sizes
ArrayResize(get_values,3); ArrayResize(get_times,3); ArrayResize(positions,3);
//--- Counters
int i=0,k=0;
//--- Start to search for fractures
while(i<100)
{
double v=values[i];
//--- We are not interested in empty values
if(v!=0.0)
{
//--- Remember the bar number
positions[k]=i;
//--- Remember the value of a zigzag on the fracture
get_values[k]=values[i];
PrintFormat("%s: Zigzag[%d]=%G",__FUNCTION__,i,values[i]);
//--- Increase the counter
k++;
//--- If two fractures found, break the loop
if(k>2) break;
}
i++;
}
//--- Define the order of access to the arrays as in a timeseries
ArraySetAsSeries(times,true);
ArraySetAsSeries(get_times,true);
if(CopyTime(_Symbol,_Period,0,size,times)<=0)
{
PrintFormat("%s: Failed to copy %d values from CopyTime(). Error code %d",
__FUNCTION__,size,GetLastError());
return false;
}
//--- Open the bar open time, on which the last 2 fractures occurred
get_times[0]=times[positions[1]];// The last but one value will be written as the first fracture
get_times[1]=times[positions[2]];// The value third from the end will be the second fracture
PrintFormat("%s: first=%s,
second=%s",__FUNCTION__,TimeToString(get_times[1]),TimeToString(get_
//--- Successful
1131
Chart Operations
return true;
}
See also
ChartApplyTemplate(), Resources
1132
Chart Operations
ChartWindowFind
The function returns the number of a subwindow where an indicator is drawn. There are 2 variants of
the function.
1. The function searches in the indicated chart for the subwindow with the specified "short name" of
the indicator (the short name is displayed in the left top part of the subwindow), and it returns the
subwindow number in case of success.
int ChartWindowFind(
long
chart_id,
// chart identifier
string
indicator_shortname
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.
Example:
#property script_show_inputs
//--- input parameters
input string
shortname="MACD(12,26,9)";
//+------------------------------------------------------------------+
//| Returns number of the chart window with this indicator
//+------------------------------------------------------------------+
int GetIndicatorSubWindowNumber(long chartID=0,string short_name="")
1133
Chart Operations
{
int window=-1;
//--if((ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR)
{
//--- the function is called from the indicator, name is not required
window=ChartWindowFind();
}
else
{
//--- the function is called from an Expert Advisor or script
window=ChartWindowFind(0,short_name);
if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError());
}
//--return(window);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--int window=GetIndicatorSubWindowNumber(0,shortname);
if(window!=-1)
Print("Indicator "+shortname+" is in the window #"+(string)window);
else
Print("Indicator "+shortname+" is not found. window = "+(string)window);
}
See also
ObjectCreate(), ObjectFind()
1134
Chart Operations
ChartTimePriceToXY
Converts the coordinates of a chart from the time/price representation to the X and Y coordinates.
bool ChartTimePriceToXY(
long
chart_id,
// Chart ID
int
sub_window,
datetime
time,
double
price,
int&
x,
int&
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart subwindow. 0 means the main chart window.
time
[in] The time value on the chart, for which the value in pixels along the X axis will be received.
The origin is in the upper left corner of the main chart window.
price
[in] The price value on the chart, for which the value in pixels along the Y axis will be received.
The origin is in the upper left corner of the main chart window.
x
[out] The variable, into which the conversion of time to X will be received.
y
[out] The variable, into which the conversion of price to Y will be received.
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
See also
ChartXYToTimePrice()
1135
Chart Operations
ChartXYToTimePrice
Converts the X and Y coordinates on a chart to the time and price values.
bool ChartXYToTimePrice(
long
chart_id,
// Chart ID
int
x,
int
y,
int&
sub_window,
datetime&
time,
double&
price
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
x
[in] The X coordinate.
y
[in] The Y coordinate.
sub_window
[out] The variable, into which the chart subwindow number will be written. 0 means the main
chart window.
time
[out] The time value on the chart, for which the value in pixels along the X axis will be received.
The origin is in the upper left corner of the main chart window.
price
[out] The price value on the chart, for which the value in pixels along the Y axis will be received.
The origin is in the upper left corner of the main chart window.
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| ChartEvent function
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the event parameters on the chart
1136
Chart Operations
Comment(__FUNCTION__,": id=",id," lparam=",lparam," dparam=",dparam," sparam=",sparam);
//--- If this is an event of a mouse click on the chart
if(id==CHARTEVENT_CLICK)
{
//--- Prepare variables
int
=(int)lparam;
int
=(int)dparam;
datetime dt
=0;
double
price =0;
int
window=0;
Y=%d
=>
Time=%s
Price=%G",window,x,y,TimeToString(dt),pric
Price=%G
=>
X=%d
Y=%d",TimeToString(dt),price,x,y);
else
Print("ChartTimePriceToXY return error code: ",GetLastError());
//--- delete lines
ObjectDelete(0,"V Line");
ObjectDelete(0,"H Line");
//--- create horizontal and vertical lines of the crosshair
ObjectCreate(0,"H Line",OBJ_HLINE,window,dt,price);
ObjectCreate(0,"V Line",OBJ_VLINE,window,dt,price);
ChartRedraw(0);
}
else
Print("ChartXYToTimePrice return error code: ",GetLastError());
Print("+--------------------------------------------------------------+");
}
}
See also
ChartTimePriceToXY()
1137
Chart Operations
ChartOpen
Opens a new chart with the specified symbol and period.
long ChartOpen(
string
symbol,
ENUM_TIMEFRAMES period
// Symbol name
// 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
If successful, it returns the opened chart ID. Otherwise returns 0.
Note
The maximum possible number of simultaneously open charts in the terminal can't exceed the
CHARTS_MAX value.
1138
Chart Operations
ChartFirst
Returns the ID of the first chart of the client terminal.
long ChartFirst();
Return Value
Chart ID.
1139
Chart Operations
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:
//--- variables for chart ID
long currChart,prevChart=ChartFirst();
int i=0,limit=100;
Print("ChartFirst =",ChartSymbol(prevChart)," ID =",prevChart);
while(i<limit)// We have certainly not more than 100 open charts
{
currChart=ChartNext(prevChart); // Get the new chart ID by using the previous chart ID
if(currChart<0) break;
Print(i,ChartSymbol(currChart)," ID =",currChart);
prevChart=currChart;// let's save the current chart ID for the ChartNext()
i++;// Do not forget to increase the counter
}
1140
Chart Operations
ChartClose
Closes the specified chart.
bool ChartClose(
long chart_id=0
// Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
If successful, returns true, otherwise false.
1141
Chart Operations
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
If chart does not exist, the result will be an empty string.
See also
ChartSetSymbolPeriod
1142
Chart Operations
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.
1143
Chart Operations
ChartRedraw
This function calls a forced redrawing of a specified chart.
void ChartRedraw(
long chart_id=0
// Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Note
Usually it is used after changing the object properties.
See also
Objects functions
1144
Chart Operations
ChartSetDouble
Sets a value for a corresponding property of the specified chart. Chart property should be of a double
type. The command is added to chart messages queue and will be executed after processing of all
previous commands.
bool ChartSetDouble(
long
chart_id,
// Chart ID
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
Returns true if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
1145
Chart Operations
ChartSetInteger
Sets a value for a corresponding property of the specified chart. Chart property must be
datetime,int,color,boolorchar. The command is added to chart messages queue and will be
executed after processing of all previous commands.
bool ChartSetInteger(
long
chart_id,
// Chart ID
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
Returns true if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
1146
Chart Operations
ChartSetString
Sets a value for a corresponding property of the specified chart. Chart property must be of the string
type. The command is added to chart messages queue and will be executed after processing of all
previous commands.
bool ChartSetString(
long chart_id,
// Chart ID
int
// Property ID
prop_id,
string
str_value
// Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. Its value can be one of the ENUM_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
Returns true if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
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
1147
Chart Operations
ChartGetDouble
Returns the value of a corresponding property of the specified chart. Chart property must be of double
type. There are 2 variants of the function calls.
1. Returns the property value directly.
double ChartGetDouble(
long chart_id,
// Chart ID
int
prop_id,
// Property ID
int
sub_window=0
);
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
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_DOUBLE values.
sub_window
[in] Number of the chart subwindow. For the first case, the default value is 0 (main chart
window). The most of the properties do not require a subwindow number.
double_var
[out] Target variable of double type for the requested property.
Return Value
The value of double type.
For the second call case it returns true if the specified property is available and its value has been
placed into double_var variable, otherwise returns false. To get an additional information about the
error, it is necessary to call the function GetLastError().
Example:
void OnStart()
{
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,0);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,0);
Print("CHART_PRICE_MIN =",priceMin);
1148
Chart Operations
Print("CHART_PRICE_MAX =",priceMax);
}
1149
Chart Operations
ChartGetInteger
Returns the value of a corresponding property of the specified chart. Chart property must be of
datetime,intorbool type. There are 2 variants of the function calls.
1. Returns the property value directly.
long ChartGetInteger(
long chart_id,
// Chart ID
int
prop_id,
// Property ID
int
sub_window=0
);
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
);
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
The value of long type.
For the second call case it returns true if specified property is available and its value has been
stored into long_var variable, otherwise returns false. To get additional information about the error,
it is necessary to call the function GetLastError().
Example:
void OnStart()
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
Print("CHART_HEIGHT_IN_PIXELS =",height,"pixels");
1150
Chart Operations
Print("CHART_WIDTH_IN_PIXELS =",width,"pixels");
}
1151
Chart Operations
ChartGetString
Returns the value of a corresponding property of the specified chart. Chart property must be of string
type. There are 2 variants of the function call.
1. Returns the property value directly.
string ChartGetString(
long chart_id,
// Chart ID
int
// Property ID
prop_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
);
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
The value of string type.
For the second call case it returns true if the specified property is available and its value has been
stored into string_var variable, otherwise returns false. To get additional information about the
error, it is necessary to call the function GetLastError().
Note
ChartGetString can be used for reading comments plotted on the chart using the Comment or
ChartSetString functions.
Example:
void OnStart()
{
ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!");
ChartRedraw();
Sleep(1000);
string comm=ChartGetString(0,CHART_COMMENT);
Print(comm);
1152
Chart Operations
}
See also
Comment, ChartSetString
1153
Chart Operations
ChartNavigate
Performs shift of the specified chart by the specified number of bars relative to the specified position
in the chart.
bool ChartNavigate(
long chart_id,
// Chart ID
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. Positive value means the right shift (to the end of chart),
negative value means the left shift (to the beginning of chart). The zero shift can be used to
navigate to the beginning or end of chart.
Return Value
Returns true if successful, otherwise returns false.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- get handle of the current chart
long handle=ChartID();
string comm="";
if(handle>0) // if successful, additionally set up the chart
{
//--- disable auto scroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- set a shift from the right chart border
ChartSetInteger(handle,CHART_SHIFT,true);
//--- draw candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- set the display mode for tick volumes
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
//--- prepare a text to output in Comment()
comm="Scroll 10 bars to the right of the history start";
//--- show comment
1154
Chart Operations
Comment(comm);
//--- scroll 10 bars to the right of the history start
ChartNavigate(handle,CHART_BEGIN,10);
//--- get the number of the first bar visible on the chart (numeration like in timeseries)
long first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
//--- add line feed character
comm=comm+"\r\n";
//--- add to comment
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
//--- show comment
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);
//--- add to the comment text
comm=comm+"\r\n"+"Scroll 10 bars to the left of the right chart border";
Comment(comm);
//--- scroll 10 bars to the left of the right chart border
ChartNavigate(handle,CHART_END,-10);
//--- get the number of the first bar visible on the chart (numeration like in timeseries)
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);
//--- new block of chart scrolling
comm=comm+"\r\n"+"Scroll 300 bars to the right of the history start";
Comment(comm);
//--- scroll 300 bars to the right of the history start
ChartNavigate(handle,CHART_BEGIN,300);
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);
//--- new block of chart scrolling
comm=comm+"\r\n"+"Scroll 300 bars to the left of the right chart border";
Comment(comm);
//--- scroll 300 bars to the left of the right chart border
ChartNavigate(handle,CHART_END,-300);
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
}
1155
Chart Operations
}
1156
Chart Operations
ChartID
Returns the ID of the current chart.
long ChartID();
Return Value
Value of long type.
1157
Chart Operations
ChartIndicatorAdd
Adds an indicator with the specified handle into a specified chart window. Indicator and chart should
be generated on the same symbol and time frame.
bool ChartIndicatorAdd(
long chart_id,
// chart ID
int
sub_window
int
indicator_handle
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart sub-window. 0 means the main chart window. To add an indicator in
a new window, the parameter must be one greater than the index of the last existing window, i.e.
equal to CHART_WINDOWS_TOTAL. If the value of the parameter is greater than
CHART_WINDOWS_TOTAL, a new window will not be created, and the indicator will not be added.
indicator_handle
[in] The handle of the indicator.
Return Value
The function returns true in case of success, otherwise it returns false. In order to obtain
information about the error, call the GetLastError() function. Error 4114 means that a chart and an
added indicator differ by their symbol or time frame.
Note
If an indicator that should be drawn in a separate subwindow (for example, built-in iMACD or a
custom indicator with specified #property indicator_separate_window property) is applied to the
main chart window, it may not be visible though it will still be present in the list of indicators. This
means that the scale of the indicator is different from the scale of the price chart, and applied
indicator's values do not fit in the displayed range of the price chart. In this case, GetLastError()
returns zero code indicating the absence of an error. The values of such "invisible" indicator can be
seen in Data Window and received from other MQL5 applications.
Example:
#property description "Expert Advisor demonstrating the work with ChartIndicatorAdd() function."
#property description "After launching on the chart (and receiving the error in Journal), open"
#property description "the Expert Advisor's properties and specify correct <symbol> and <period> pa
#property description "MACD indicator will be added on the chart."
//--- input parameters
input string
symbol="AUDUSD";
// symbol name
// time frame
input int
fast_ema_period=12;
input int
slow_ema_period=26;
1158
Chart Operations
input int
signal_period=9;
// signal period
//+------------------------------------------------------------------+
int OnInit()
{
//--indicator_handle=iMACD(symbol,period,fast_ema_period,slow_ema_period,signal_period,apr);
//--- try to add the indicator on the chart
if(!AddIndicator())
{
//--- AddIndicator() function refused to add the indicator on the chart
int answer=MessageBox("Do you want to add MACD on the chart anyway?",
"Incorrect symbol and/or time frame for adding the indicator",
MB_YESNO // "Yes" and "No" selection buttons will be shown
);
//--- if a user still insists on incorrect usage of ChartIndicatorAdd()
if(answer==IDYES)
{
//--- first of all, a Journal entry will be made about that
PrintFormat("Attention! %s: Trying to add MACD(%s/%s) indicator on %s/%s chart. Receiving
__FUNCTION__,symbol,EnumToString(period),_Symbol,EnumToString(_Period));
//--- receive the number of a new subwindow, to which we will try to add the indicator
int subwindow=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
//--- now make an attempt resulting in error
if(!ChartIndicatorAdd(0,subwindow,indicator_handle))
PrintFormat("Failed to add MACD indicator on %d chart window. Error code
subwindow,GetLastError());
}
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
// Expert Advisor performs nothing
}
//+------------------------------------------------------------------+
//| Function for checking and adding the indicator on the chart
//+------------------------------------------------------------------+
bool AddIndicator()
{
//--- displayed message
%d",
1159
Chart Operations
string message;
//--- check if the indicator symbol and chart symbol match each other
if(symbol!=_Symbol)
{
message="Displaying the use of Demo_ChartIndicatorAdd() function:";
message=message+"\r\n";
message=message+"Unable to add the indicator calculated on another symbol on the chart.";
message=message+"\r\n";
message=message+"Specify the chart symbol in Expert Advisor's property - "+_Symbol+".";
Alert(message);
//--- premature exit, the indicator will not be added on the chart
return false;
}
//--- check if the indicator's and chart's time frames match each other
if(period!=_Period)
{
message="Unable to add the indicator calculated on another time frame on the chart.";
message=message+"\r\n";
indicator_handle=iMACD(symbol,period,fast_ema_period,slow_ema_period,signal_period,apr);
if(indicator_handle==INVALID_HANDLE)
{
Print("Failed to create MACD indicator. Error code ",GetLastError());
}
}
//--- reset the error code
ResetLastError();
//--- apply the indicator to the chart
Print(__FUNCTION__,"
%d",
1160
Chart Operations
See Also
ChartIndicatorDelete(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate()
1161
Chart Operations
ChartIndicatorDelete
Removes an indicator with a specified name from the specified chart window.
bool ChartIndicatorDelete(
long
chart_id,
// chart id
int
sub_window
const string
indicator_shortname
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
const indicator_shortname
[in] The short name of the indicator which is set in the INDICATOR_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.
Example of deleting an indicator after initialization has failed:
//+------------------------------------------------------------------+
//|
Demo_ChartIndicatorDelete.mq5 |
//|
1162
Chart Operations
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"Histogram"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
first_param=1;
input int
second_param=2;
input int
third_param=3;
input bool
wrong_init=true;
HistogramBuffer[];
string
shortname;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
int res=INIT_SUCCEEDED;
//--- Link the HistogramBuffer array to the indicator buffer
SetIndexBuffer(0,HistogramBuffer,INDICATOR_DATA);
//--- Construct a short indicator name based on input parameters
shortname=StringFormat("Demo_ChartIndicatorDelete(%d,%d,%d)",
first_param,second_param,third_param);
IndicatorSetString(INDICATOR_SHORTNAME,shortname);
//--- If forced completion of an indicator is set, return a non-zero value
if(wrong_init) res=INIT_FAILED;
return(res);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
1163
Chart Operations
const long &volume[],
const int &spread[])
{
//--- Starting position for working in a loop
int start=prev_calculated-1;
if(start<0) start=0;
//--- Fill in the indicator buffer with values
for(int i=start;i<rates_total;i++)
{
HistogramBuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| A handler of the Deinit event
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
if(reason==REASON_INITFAILED)
{
PrintFormat("An indicator with a short name %s (file %s) deletes itself from the chart",short
int window=ChartWindowFind();
bool res=ChartIndicatorDelete(0,window,shortname);
//--- Analyse the result of call of ChartIndicatorDelete()
if(!res)
{
PrintFormat("Failed to delete indicator %s from window #%d. Error code %d",
shortname,window,GetLastError());
}
}
}
See also
ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorSetString()
1164
Chart Operations
ChartIndicatorGet
Returns the handle of the indicator with the specified short name in the specified chart window.
int ChartIndicatorGet(
long
chart_id,
// Chart ID
int
sub_window
const string
indicator_shortname
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart subwindow. 0 means the main chart window.
const indicator_shortname
[in] The short name if the indicator, which is set in the INDICATOR_SHORTNAME property using
the IndicatorSetString() function. To get the short name of an indicator, use the
ChartIndicatorName() function.
Return Value
Returns an indicator handle if successful, otherwise returns INVALID_HANDLE. To get information
about the error, call the GetLastError() function.
Note
When creating an indicator, be careful forming its short name, which is written in the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that a
short name should contain the values of input parameters of the indicator, since the indicator is
identified in the ChartIndicatorGet() function based on its short name.
Another way to identify the indicator is to get a list of its parameters for a given handle using the
IndicatorParameters() function and then to analyze the obtained values.
Example:
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- The number of windows on the chart (at least one main window is always present)
int windows=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
//--- Check all windows
for(int w=0;w<windows;w++)
{
//--- the number of indicators in this window/subwindow
int total=ChartIndicatorsTotal(0,w);
//--- Go through all indicators in the window
1165
Chart Operations
for(int i=0;i<total;i++)
{
//--- get the short name of an indicator
string name=ChartIndicatorName(0,w,i);
//--- get the handle of an indicator
int handle=ChartIndicatorGet(0,w,name);
//--- Add to log
PrintFormat("Window=%d,
index=%d,
name=%s,
handle=%d",w,i,name,handle);
//--- You should obligatorily release the indicator handle when it is no longer needed
IndicatorRelease(handle);
}
}
}
See also
ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), IndicatorParameters()
1166
Chart Operations
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
int
index
// index of the indicator in the list of indicators added to the chart subw
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
index
[in] the index of the indicator in the list of indicators. The numeration of indicators start with
zero, i.e. the first indicator in the list has the 0 index. To obtain the number of indicators in the
list use the ChartIndicatorsTotal() function.
Return Value
The short name of the indicator which is set in the INDICATOR_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()
1167
Chart Operations
ChartIndicatorsTotal
Returns the number of all indicators applied to the specified chart window.
int ChartIndicatorsTotal(
long chart_id,
// chart id
int
sub_window
);
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()
1168
Chart Operations
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
Value of int type.
Example:
int myWindow=ChartWindowOnDropped();
int windowsTotal=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("Script is running on the window #"+myWindow+
". Total windows on the chart "+ChartSymbol()+":",windowsTotal);
See also
ChartPriceOnDropped, ChartTimeOnDropped, ChartXOnDropped, ChartYOnDropped
1169
Chart Operations
ChartPriceOnDropped
Returns the price coordinate corresponding to the chart point the Expert Advisor or script has been
dropped to.
double ChartPriceOnDropped();
Return Value
Value of double type.
Example:
double p=ChartPriceOnDropped();
Print("ChartPriceOnDropped() = ",p);
See also
ChartXOnDropped, ChartYOnDropped
1170
Chart Operations
ChartTimeOnDropped
Returns the time coordinate corresponding to the chart point the Expert Advisor or script has been
dropped to.
datetime ChartTimeOnDropped();
Return Value
Value of datetime type.
Example:
datetime t=ChartTimeOnDropped();
Print("Script was dropped on the "+t);
See also
ChartXOnDropped, ChartYOnDropped
1171
Chart Operations
ChartXOnDropped
Returns the X coordinate of the chart point the Expert Advisor or script has been dropped to.
int ChartXOnDropped();
Return Value
The X coordinate value.
Note
X axis direction from left to right.
Example:
int X=ChartXOnDropped();
int Y=ChartYOnDropped();
Print("(X,Y) = ("+X+","+Y+")");
See also
ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped
1172
Chart Operations
ChartYOnDropped
Returns the Y coordinateof the chart point the Expert Advisor or script has been dropped to.
int ChartYOnDropped();
Return Value
The Y coordinate value.
Note
Y axis direction from top to bottom.
See also
ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped
1173
Chart Operations
ChartSetSymbolPeriod
Changes the symbol and period of the specified chart. The function is asynchronous, i.e. it sends the
command and does not wait for its execution completion. The command is added to chart messages
queue and will be executed after processing of all previous commands.
bool ChartSetSymbolPeriod(
long
chart_id,
// Chart ID
string
symbol,
// Symbol name
ENUM_TIMEFRAMES period
// Period
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
symbol
[in] Chart symbol. NULL value means the current chart symbol (Expert Advisor is attached to)
period
[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current
chart period.
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note
The symbol/period change leads to the re-initialization of the Expert Advisor, attached to a chart.
See also
ChartSymbol, ChartPeriod
1174
Chart Operations
ChartScreenShot
The function provides a screenshot of the chart in its current state in the GIF, PNG or BMP format
depending on specified extension.
bool ChartScreenShot(
long
chart_id,
// Chart ID
string
filename,
// Symbol name
int
width,
// Width
int
height,
// Height
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT
// Alignment type
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in the \Files
directory.
width
[in] Screenshot width in pixels.
height
[in] Screenshot height in pixels.
align_mode=ALIGN_RIGHT
[in] Output mode of a narrow screenshot. A value of the ENUM_ALIGN_MODE enumeration.
ALIGN_RIGHT means align to the right margin (the output from the end). ALIGN_LEFT means Left
justify.
Return Value
Returns true if successful, otherwise false.
Note
If you need to take a screenshot from a chart from a certain position, first it's necessary to position
the graph using the ChartNavigate() function. If the horizontal size of the screenshot is smaller than
the chart window, either the right part of the chart window, or its left part is output, depending on
the align_mode settings.
Example:
#property description "The Expert Advisor demonstrates how to create a series of screenshots of the
#property description "chart using the ChartScreenShot() function. For convenience, the file name i
#property description "shown on the chart. The height and width of images is defined through macros
#define
WIDTH
#define
HEIGHT 600
800
1175
Chart Operations
//--- input parameters
input int
pictures=5;
int
mode=-1;
int
bars_shift=300;// The number of bars when scrolling the chart using ChartNavigate()
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
void OnInit()
{
//--- Disable chart autoscroll
ChartSetInteger(0,CHART_AUTOSCROLL,false);
//--- Set the shift of the right edge of the chart
ChartSetInteger(0,CHART_SHIFT,true);
//--- Show a candlestick chart
ChartSetInteger(0,CHART_MODE,CHART_CANDLES);
//--Print("Preparation of the Expert Advisor is completed");
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
//--}
//+------------------------------------------------------------------+
//| ChartEvent function
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the name of the function, call time and event identifier
Print(__FUNCTION__,TimeCurrent(),"
id=",id,"
mode=",mode);
//--- Handle the CHARTEVENT_CLICK event ("A mouse click on the chart")
if(id==CHARTEVENT_CLICK)
{
//--- Initial shift from the chart edge
int pos=0;
//--- Operation with the left chart edge
if(mode>0)
{
//--- Scroll the chart to the left edge
ChartNavigate(0,CHART_BEGIN,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name
1176
Chart Operations
string name="ChartScreenShot"+"CHART_BEGIN"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL5\Files\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_LEFT))
Print("We've saved the screenshot ",name);
//--pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the right
ChartNavigate(0,CHART_CURRENT_POS,bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
else // Operation with the right chart edge
{
//--- Scroll the chart to the right edge
ChartNavigate(0,CHART_END,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name
string name="ChartScreenShot"+"CHART_END"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL5\Files\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_RIGHT))
Print("We've saved the screenshot ",name);
//--pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the right
ChartNavigate(0,CHART_CURRENT_POS,-bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
}
See also
ChartNavigate(), Resources
1177
Trade Functions
Trade Functions
This is the group of functions intended for managing trading activities.
Trading functions can be used in Expert Advisors and scripts. Trading functions can be called only if in
the properties of the Expert Advisor or script the "Allow live trading" checkbox is enabled.
Trading can be allowed or prohibited depending on various factors described in the Trade Permission
section.
Function
Action
OrderCalcMargin
OrderCalcProfit
OrderCheck
OrderSend
OrderSendAsync
PositionsTotal
PositionGetSymbol
PositionSelect
PositionSelectByTicket
PositionGetDouble
PositionGetInteger
PositionGetString
PositionGetTicket
OrdersTotal
OrderGetTicket
OrderSelect
OrderGetDouble
1178
Trade Functions
OrderGetInteger
OrderGetString
HistorySelect
HistorySelectByPosition
HistoryOrderSelect
HistoryOrdersTotal
HistoryOrderGetTicket
HistoryOrderGetDouble
HistoryOrderGetInteger
HistoryOrderGetString
HistoryDealSelect
HistoryDealsTotal
HistoryDealGetTicket
HistoryDealGetDouble
HistoryDealGetInteger
HistoryDealGetString
1179
Trade Functions
OrderCalcMargin
The function calculates the margin required for the specified order type, on the current account, in the
current market environment not taking into account current pending orders and open positions. It
allows the evaluation of margin for the trade operation planned. The value is returned in the account
currency.
bool OrderCalcMargin(
ENUM_ORDER_TYPE
action,
// type of order
string
symbol,
// symbol name
double
volume,
// volume
double
price,
// open price
double&
margin
);
Parameters
action
[in] The order type, can be one of the values 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
1180
Trade Functions
OrderCalcProfit
The function calculates the profit for the current account, in the current market conditions, based on
the parameters passed. The function is used for pre-evaluation of the result of a trade operation. The
value is returned in the account currency.
bool OrderCalcProfit(
ENUM_ORDER_TYPE
action,
string
symbol,
// symbol name
double
volume,
// volume
double
price_open,
// open price
double
price_close,
// close price
double&
profit
);
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
1181
Trade Functions
OrderCheck
The OrderCheck() function checks if there are enough money to execute a required trade operation.
The check results are placed to the fields of the MqlTradeCheckResult structure.
bool OrderCheck(
MqlTradeRequest&
request,
MqlTradeCheckResult& result
// request structure
// 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.
However, this is not an indication that the requested trade operation is sure to be successfully
executed. For a more detailed description of the function execution result, analyze the fields of the
result structure.
In order to obtain information about the error, call the GetLastError() function.
See also
OrderSend(), Trade Operation Types, Trade Request Structure, Structure of Request Check Results,
Structure of a Trade Request Result
1182
Trade Functions
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
);
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. However, this is not
a sign of successful execution of a trade operation. For a more detailed description of the
function execution result, analyze the fields of result structure.
Note
The trade requests go through several stages of checking on a trade server. First of all, it checks if
all the required fields of the request parameter are filled out correctly. If there are no errors, the
server accepts the order for further processing. If the order is successfully accepted by the trade
server, the 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 that the successful completion of the OrderSend() method operation does not
always mean a successful deal completion when placing a market order. Check the retcode value
containing trade server return code, and values of deal or order field depending on the type of
operation in the returned result.
Each accepted order is stored on the trade server awaiting processing until one of the conditions for
its execution occurs:
expiration,
appearance of an opposite request,
1183
Trade Functions
order execution when the execution price appears,
a request to cancel the order is received.
At the moment of the order processing, the trade server sends to the terminal a message about the
occurrence of the Trade event, which can be processed by the OnTrade() function.
The result of executing the trade request on a server sent by OrderSend() function can be tracked
by OnTradeTransaction handler. It should be noted that OnTradeTransaction handler will be called
several times when executing one trade request.
For example, when sending a market buy order, it is handled, an appropriate buy order is created
for the account, the order is then executed and removed from the list of the open ones, then it is
added to the orders history, an appropriate deal is added to the history and a new position is
created. OnTradeTransaction function will be called for each of these events.
Example:
//--- value for ORDER_MAGIC
input long order_magic=55555;
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- make sure that the account is demo
if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL)
{
Alert("Script operation is not allowed on a live account!");
return;
}
//--- place or delete order
if(GetOrdersTotalByMagic(order_magic)==0)
{
//--- no current orders - place an order
uint res=SendRandomPendingOrder(order_magic);
Print("Return code of the trade server ",res);
}
else // there are orders - delete orders
{
DeleteAllOrdersByMagic(order_magic);
}
//--}
//+------------------------------------------------------------------+
//| Receives the current number of orders with specified ORDER_MAGIC |
//+------------------------------------------------------------------+
int GetOrdersTotalByMagic(long const magic_number)
{
ulong order_ticket;
int total=0;
//--- go through all pending orders
1184
Trade Functions
for(int i=0;i<OrdersTotal();i++)
if((order_ticket=OrderGetTicket(i))>0)
if(magic_number==OrderGetInteger(ORDER_MAGIC)) total++;
//--return(total);
}
//+------------------------------------------------------------------+
//| Deletes all pending orders with specified ORDER_MAGIC
//+------------------------------------------------------------------+
void DeleteAllOrdersByMagic(long const magic_number)
{
ulong order_ticket;
//--- go through all pending orders
for(int i=OrdersTotal()-1;i>=0;i--)
if((order_ticket=OrderGetTicket(i))>0)
//--- order with appropriate ORDER_MAGIC
if(magic_number==OrderGetInteger(ORDER_MAGIC))
{
MqlTradeResult result={0};
MqlTradeRequest request={0};
request.order=order_ticket;
request.action=TRADE_ACTION_REMOVE;
OrderSend(request,result);
//--- write the server reply to log
Print(__FUNCTION__,": ",result.comment," reply code ",result.retcode);
}
//--}
//+------------------------------------------------------------------+
//| Sets a pending order in a random way
//+------------------------------------------------------------------+
uint SendRandomPendingOrder(long const magic_number)
{
//--- prepare a request
MqlTradeRequest request={0};
request.action=TRADE_ACTION_PENDING;
request.magic=magic_number;
// ORDER_MAGIC
request.symbol=_Symbol;
// symbol
request.volume=0.1;
request.sl=0;
request.tp=0;
// order type
// open price
1185
Trade Functions
Print(__FUNCTION__,":",result.comment);
if(result.retcode==10016) Print(result.bid,result.ask,result.price);
//--- return code of the trade server reply
return result.retcode;
}
//+------------------------------------------------------------------+
//| Returns type of a pending order in a random way
//+------------------------------------------------------------------+
ENUM_ORDER_TYPE GetRandomType()
{
int t=MathRand()%4;
//---
0<=t<4
switch(t)
{
case(0):return(ORDER_TYPE_BUY_LIMIT);
case(1):return(ORDER_TYPE_SELL_LIMIT);
case(2):return(ORDER_TYPE_BUY_STOP);
case(3):return(ORDER_TYPE_SELL_STOP);
}
//--- incorrect value
return(WRONG_VALUE);
}
//+------------------------------------------------------------------+
//| Returns price in a random way
//+------------------------------------------------------------------+
double GetRandomPrice(ENUM_ORDER_TYPE type)
{
int t=(int)type;
//--- stop levels for the symbol
int distance=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
//--- receive data of the last tick
MqlTick last_tick={0};
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);
}
1186
Trade Functions
See also
Trade Operation Types, Trade Request Structure, Structure of Request Check Results, Structure of a
Trade Request Result
1187
Trade Functions
OrderSendAsync
The OrderSendAsync() function is used for conducting asynchronous trade operations without waiting
for the trade server's response to a sent request. The function is designed for high-frequency trading,
when under the terms of the trading algorithm it is unacceptable to waste time waiting for a response
from the server.
bool OrderSendAsync(
MqlTradeRequest& request,
// Request structure
MqlTradeResult& result
// Response structure
);
Parameters
request
[in] A pointer to a structure of the MqlTradeRequest type that describes the trade action of the
client.
result
[in,out] A pointer to a structure of the MqlTradeResult type that describes the result of a trade
operation in case of successful execution of the function (if true is returned).
Return Value
Returns true if the request is sent to a trade server. In case the request is not sent, it returns false.
In case the request is sent, in the result variable the response code contains
TRADE_RETCODE_PLACED value (code 10008) "order placed". Successful execution means only the
fact of sending, but does not give any guarantee that the request has reached the trade server and
has been accepted for processing. When processing the received request, a trade server sends a
reply to a client terminal notifying of change in the current state of positions, orders and deals,
which leads to the generation of the Trade event.
The result of executing the trade request on a server sent by OrderSendAsync() function can be
tracked by OnTradeTransaction handler. It should be noted that OnTradeTransaction handler will be
called several times when executing one trade request.
For example, when sending a market buy order, it is handled, an appropriate buy order is created
for the account, the order is then executed and removed from the list of the open ones, then it is
added to the orders history, an appropriate deal is added to the history and a new position is
created. OnTradeTransaction function will be called for each of these events. To get such a data,
the function parameters should be analyzed:
trans - this parameter gets MqlTradeTransaction structure describing a trade transaction applied
to a trade account;
request - this parameter gets MqlTradeRequest structure describing the trade request resulted in a
trade transaction;
result - this parameter gets MqlTradeResult structure describing a trade request execution result.
Note
In terms of purposes and parameters, the function is similar to OrderSend(), but unlike it, it is
asynchronous, i.e. does not hold the program operation while waiting for the function execution
result. You can compare the rate of trade operations of these two functions using the sample Expert
Advisor.
1188
Trade Functions
Example:
#property description "Expert Advisor for sending trade requests "
" using OrderSendAsync() function.\r\n"
#property description "Handling trading events using"
" OnTrade() and OnTradeTransaction() handler functions is displayed\r\n"
#property description "Expert Advisor parameters allow setting Magic Number"
" (unique ID) "
#property description "and the mode of displaying messages in Experts log. All details are displaye
//--- input parameters
input int
MagicNumber=1234567;
// Expert Advisor ID
//+------------------------------------------------------------------+
int OnInit()
{
//--- check if autotrading is allowed
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
{
Alert("Autotrading in the terminal is disabled, Expert Advisor will be removed.");
ExpertRemove();
return(-1);
}
//--- unable to trade on a real account
if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL)
{
Alert("Expert Advisor cannot trade on a real account!");
ExpertRemove();
return(-2);
}
//--- check if it is possible to trade on this account (for example, trading is impossible when usi
if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
{
Alert("Trading on this account is disabled");
ExpertRemove();
return(-3);
}
//--- save the time of launching the Expert Advisor for receiving trading history
history_start=TimeCurrent();
//--CreateBuySellButtons();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
1189
Trade Functions
void OnDeinit(const int reason)
{
//--- delete all graphical objects
ObjectDelete(0,"Buy");
ObjectDelete(0,"Sell");
//--}
//+------------------------------------------------------------------+
//| TradeTransaction function
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
//--- heading named after trading event's handler function
Print("=> ",__FUNCTION__," at ",TimeToString(TimeCurrent(),TIME_SECONDS));
//--- receive transaction type as enumeration value
ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is a result of request handling
if(type==TRADE_TRANSACTION_REQUEST)
{
//--- display transaction name
Print(EnumToString(type));
//--- then display the string description of the handled request
Print("------------RequestDescription\r\n",
RequestDescription(request,DescriptionModeFull));
//--- and show description of the request result
Print("------------ ResultDescription\r\n",
TradeResultDescription(result,DescriptionModeFull));
}
else // display full description of the transaction for transactions of another type
{
Print("------------ TransactionDescription\r\n",
TransactionDescription(trans,DescriptionModeFull));
}
//--}
//+------------------------------------------------------------------+
//| Trade function
//+------------------------------------------------------------------+
void OnTrade()
{
//--- static members for storing trading account status
static int prev_positions=0,prev_orders=0,prev_deals=0,prev_history_orders=0;
//--- request trading history
bool update=HistorySelect(history_start,TimeCurrent());
PrintFormat("HistorySelect(%s , %s) = %s",
TimeToString(history_start),TimeToString(TimeCurrent()),(string)update);
//--- heading named after trading event's handler function
1190
Trade Functions
Print("=> ",__FUNCTION__," at ",TimeToString(TimeCurrent(),TIME_SECONDS));
//--- display handler's name and the number of orders at the moment of handling
int curr_positions=PositionsTotal();
int curr_orders=OrdersTotal();
int curr_deals=HistoryOrdersTotal();
int curr_history_orders=HistoryDealsTotal();
//--- display the number of orders, positions, deals, as well as changes in parentheses
PrintFormat("PositionsTotal() = %d (%+d)",
curr_positions,(curr_positions-prev_positions));
PrintFormat("OrdersTotal() = %d (%+d)",
curr_orders,curr_orders-prev_orders);
PrintFormat("HistoryOrdersTotal() = %d (%+d)",
curr_deals,curr_deals-prev_deals);
PrintFormat("HistoryDealsTotal() = %d (%+d)",
curr_history_orders,curr_history_orders-prev_history_orders);
//--- insert a string break to view the log more conveniently
Print("");
//--- save the account status
prev_positions=curr_positions;
prev_orders=curr_orders;
prev_deals=curr_deals;
prev_history_orders=curr_history_orders;
//--}
//+------------------------------------------------------------------+
//| ChartEvent function
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- handling CHARTEVENT_CLICK event ("Clicking the chart")
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("=> ",__FUNCTION__,": sparam = ",sparam);
//--- minimum volume for a deal
double volume_min=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
//--- if "Buy" button is pressed, then buy
if(sparam=="Buy")
{
PrintFormat("Buy %s %G lot",_Symbol,volume_min);
BuyAsync(volume_min);
//--- unpress the button
ObjectSetInteger(0,"Buy",OBJPROP_STATE,false);
}
//--- if "Sell" button is pressed, then sell
if(sparam=="Sell")
{
1191
Trade Functions
PrintFormat("Sell %s %G lot",_Symbol,volume_min);
SellAsync(volume_min);
//--- unpress the button
ObjectSetInteger(0,"Sell",OBJPROP_STATE,false);
}
ChartRedraw();
}
//--}
//+------------------------------------------------------------------+
//| Returns the text description of a transaction
//+------------------------------------------------------------------+
string TransactionDescription(const MqlTradeTransaction &trans,
const bool detailed=true)
{
//--- prepare a string for returning from the function
string desc=EnumToString(trans.type)+"\r\n";
//--- all possible data is added in detailed mode
if(detailed)
{
desc+="Symbol: "+trans.symbol+"\r\n";
desc+="Deal ticket: "+(string)trans.deal+"\r\n";
desc+="Deal type: "+EnumToString(trans.deal_type)+"\r\n";
desc+="Order ticket: "+(string)trans.order+"\r\n";
desc+="Order type: "+EnumToString(trans.order_type)+"\r\n";
desc+="Order state: "+EnumToString(trans.order_state)+"\r\n";
desc+="Order time type: "+EnumToString(trans.time_type)+"\r\n";
desc+="Order expiration: "+TimeToString(trans.time_expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",trans.price)+"\r\n";
desc+="Price trigger: "+StringFormat("%G",trans.price_trigger)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",trans.price_sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",trans.price_tp)+"\r\n";
desc+="Volume: "+StringFormat("%G",trans.volume)+"\r\n";
}
//--- return a received string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the text description of the trade request
//+------------------------------------------------------------------+
string RequestDescription(const MqlTradeRequest &request,
const bool detailed=true)
{
//--- prepare a string for returning from the function
string desc=EnumToString(request.action)+"\r\n";
//--- add all available data in detailed mode
if(detailed)
{
desc+="Symbol: "+request.symbol+"\r\n";
1192
Trade Functions
desc+="Magic Number: "+StringFormat("%d",request.magic)+"\r\n";
desc+="Order ticket: "+(string)request.order+"\r\n";
desc+="Order type: "+EnumToString(request.type)+"\r\n";
desc+="Order filling: "+EnumToString(request.type_filling)+"\r\n";
desc+="Order time type: "+EnumToString(request.type_time)+"\r\n";
desc+="Order expiration: "+TimeToString(request.expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",request.price)+"\r\n";
desc+="Deviation points: "+StringFormat("%G",request.deviation)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",request.sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",request.tp)+"\r\n";
desc+="Stop Limit: "+StringFormat("%G",request.stoplimit)+"\r\n";
desc+="Volume: "+StringFormat("%G",request.volume)+"\r\n";
desc+="Comment: "+request.comment+"\r\n";
}
//--- return the received string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the text description of request handling result
//+------------------------------------------------------------------+
string TradeResultDescription(const MqlTradeResult &result,
const bool detailed=true)
{
//--- prepare the string for returning from the function
string desc="Retcode "+(string)result.retcode+"\r\n";
//--- add all available data in detailed mode
if(detailed)
{
desc+="Request ID: "+StringFormat("%d",result.request_id)+"\r\n";
desc+="Order ticket: "+(string)result.order+"\r\n";
desc+="Deal ticket: "+(string)result.deal+"\r\n";
desc+="Volume: "+StringFormat("%G",result.volume)+"\r\n";
desc+="Price: "+StringFormat("%G",result.price)+"\r\n";
desc+="Ask: "+StringFormat("%G",result.ask)+"\r\n";
desc+="Bid: "+StringFormat("%G",result.bid)+"\r\n";
desc+="Comment: "+result.comment+"\r\n";
}
//--- return the received string
return desc;
}
//+------------------------------------------------------------------+
//| Create two buttons for buying and selling
//+------------------------------------------------------------------+
void CreateBuySellButtons()
{
//--- check the object named "Buy"
if(ObjectFind(0,"Buy")>=0)
{
//--- if the found object is not a button, delete it
1193
Trade Functions
if(ObjectGetInteger(0,"Buy",OBJPROP_TYPE)!=OBJ_BUTTON)
ObjectDelete(0,"Buy");
}
else
ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0); // create "Buy" button
//--- configure "Buy" button
ObjectSetInteger(0,"Buy",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,50);
ObjectSetInteger(0,"Buy",OBJPROP_XSIZE,70);
ObjectSetInteger(0,"Buy",OBJPROP_YSIZE,30);
ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
ObjectSetInteger(0,"Buy",OBJPROP_COLOR,clrRed);
//--- check presence of the object named "Sell"
if(ObjectFind(0,"Sell")>=0)
{
//--- if the found object is not a button, delete it
if(ObjectGetInteger(0,"Sell",OBJPROP_TYPE)!=OBJ_BUTTON)
ObjectDelete(0,"Sell");
}
else
ObjectCreate(0,"Sell",OBJ_BUTTON,0,0,0); // create "Sell" button
//--- configure "Sell" button
ObjectSetInteger(0,"Sell",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSetInteger(0,"Sell",OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,"Sell",OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,"Sell",OBJPROP_XSIZE,70);
ObjectSetInteger(0,"Sell",OBJPROP_YSIZE,30);
ObjectSetString(0,"Sell",OBJPROP_TEXT,"Sell");
ObjectSetInteger(0,"Sell",OBJPROP_COLOR,clrBlue);
//--- perform forced update of the chart to see the buttons immediately
ChartRedraw();
//--}
//+------------------------------------------------------------------+
//| Buy using OrderSendAsync() asynchronous function
//+------------------------------------------------------------------+
void BuyAsync(double volume)
{
//--- prepare the request
MqlTradeRequest req={0};
req.action
=TRADE_ACTION_DEAL;
req.symbol
=_Symbol;
req.magic
=MagicNumber;
req.volume
=0.1;
req.type
=ORDER_TYPE_BUY;
req.price
=SymbolInfoDouble(req.symbol,SYMBOL_ASK);
req.deviation
=10;
req.comment
1194
Trade Functions
MqlTradeResult
res={0};
if(!OrderSendAsync(req,res))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",res.retcode);
}
//--}
//+------------------------------------------------------------------+
//| Sell using OrderSendAsync() asynchronous function
//+------------------------------------------------------------------+
void SellAsync(double volume)
{
//--- prepare the request
MqlTradeRequest req={0};
req.action
=TRADE_ACTION_DEAL;
req.symbol
=_Symbol;
req.magic
=MagicNumber;
req.volume
=0.1;
req.type
=ORDER_TYPE_SELL;
req.price
=SymbolInfoDouble(req.symbol,SYMBOL_BID);
req.deviation
=10;
req.comment
MqlTradeResult
res={0};
if(!OrderSendAsync(req,res))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",res.retcode);
}
//--}
//+------------------------------------------------------------------+
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_TRANSACTION_REQUEST
12:52:52
ExpertAdvisor (EURUSD,H1)
------------RequestDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_ACTION_DEAL
12:52:52
ExpertAdvisor (EURUSD,H1)
Symbol: EURUSD
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Deviation points: 10
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Loss: 0
1195
Trade Functions
12:52:52
ExpertAdvisor (EURUSD,H1)
Take Profit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Limit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0.1
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
------------ ResultDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
Retcode 10009
12:52:52
ExpertAdvisor (EURUSD,H1)
Request ID: 2
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0.1
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Ask: 1.29319
12:52:52
ExpertAdvisor (EURUSD,H1)
Bid: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Comment:
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
PositionsTotal() = 1 (+1)
12:52:52
ExpertAdvisor (EURUSD,H1)
OrdersTotal() = 0 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryOrdersTotal() = 2 (+2)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryDealsTotal() = 2 (+2)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
------------ TransactionDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_TRANSACTION_ORDER_ADD
12:52:52
ExpertAdvisor (EURUSD,H1)
Symbol: EURUSD
12:52:52
ExpertAdvisor (EURUSD,H1)
Deal ticket: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Price trigger: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Loss: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Take Profit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0.1
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
------------ TransactionDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_TRANSACTION_ORDER_DELETE
12:52:52
ExpertAdvisor (EURUSD,H1)
Symbol: EURUSD
12:52:52
ExpertAdvisor (EURUSD,H1)
Deal ticket: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
1196
Trade Functions
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Price trigger: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Loss: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Take Profit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0.1
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
PositionsTotal() = 1 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
OrdersTotal() = 0 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryOrdersTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryDealsTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
------------ TransactionDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_TRANSACTION_HISTORY_ADD
12:52:52
ExpertAdvisor (EURUSD,H1)
Symbol: EURUSD
12:52:52
ExpertAdvisor (EURUSD,H1)
Deal ticket: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Price trigger: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Loss: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Take Profit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
PositionsTotal() = 1 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
OrdersTotal() = 0 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryOrdersTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryDealsTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
------------ TransactionDescription
12:52:52
ExpertAdvisor (EURUSD,H1)
TRADE_TRANSACTION_DEAL_ADD
12:52:52
ExpertAdvisor (EURUSD,H1)
Symbol: EURUSD
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
1197
Trade Functions
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
Price: 1.29313
12:52:52
ExpertAdvisor (EURUSD,H1)
Price trigger: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Stop Loss: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Take Profit: 0
12:52:52
ExpertAdvisor (EURUSD,H1)
Volume: 0.1
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
12:52:52
ExpertAdvisor (EURUSD,H1)
PositionsTotal() = 1 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
OrdersTotal() = 0 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryOrdersTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
HistoryDealsTotal() = 2 (+0)
12:52:52
ExpertAdvisor (EURUSD,H1)
1198
Trade Functions
PositionsTotal
Returns the number of open positions.
int PositionsTotal();
Return Value
Value of int type.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
1199
Trade Functions
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
);
Parameters
index
[in] Number of the position in the list of open positions.
Return Value
Value of the string type. If the position was not found, an empty string will be returned. To get an
error code, call the GetLastError() function.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
See also
PositionsTotal(), PositionSelect(), Position Properties
1200
Trade Functions
PositionSelect
Chooses an open position for further working with it. Returns true if the function is successfully
completed. Returns false in case of failure. To obtain information about the error, call GetLastError().
bool PositionSelect(
string symbol
// Symbol name
);
Parameters
symbol
[in] Name of the financial security.
Return Value
Value of the bool type.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol. In this case, PositionSelect will select a position with the lowest ticket.
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 its volume, direction, etc. has
changed), but data of this position still can be obtained. To ensure receipt of fresh data about a
position, it is recommended to call PositionSelect() right before referring to them.
See also
PositionGetSymbol(), PositionsTotal(), Position Properties
1201
Trade Functions
PositionSelectByTicket
Selects an open position to work with based on the ticket number specified in the position. If
successful, returns true. Returns false if the function failed. Call GetLastError() for error details.
bool PositionSelectByTicket(
ulong
ticket
// Position ticket
);
Parameters
ticket
[in] Position ticket.
Return Value
A value of the bool type.
Note
The PositionSelectByTicket() function copies position data to the program environment. Further calls
of PositionGetDouble(), PositionGetInteger() and PositionGetString() return the previously copied
data. Even if a position does not exist already (or its size, direction etc. has changed), the data may
still be received sometimes. To make sure that you receive valid position data, it is recommended
to call PositionSelect() before you access the data.
See also
PositionGetSymbol(), PositionsTotal(), Position Properties
1202
Trade Functions
PositionGetDouble
The function returns the requested property of an open position, pre-selected using PositionGetSymbol
or PositionSelect. The position property must be of the double type. There are 2 variants of the
function.
1. Immediately returns the property value.
double PositionGetDouble(
ENUM_POSITION_PROPERTY_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 variable passed by reference by the last parameter.
bool PositionGetDouble(
ENUM_POSITION_PROPERTY_DOUBLE property_id,
// Property identifier
double&
double_var
);
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
Value of the double type. If the function fails, 0 is returned.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
1203
Trade Functions
PositionGetInteger
The function returns the requested property of an open position, pre-selected using PositionGetSymbol
or PositionSelect. The position property should be of datetime, int type. There are 2 variants of the
function.
1. Immediately returns the property value.
long PositionGetInteger(
ENUM_POSITION_PROPERTY_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
);
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
Value of the long type. If the function fails, 0 is returned.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
Example:
//+------------------------------------------------------------------+
//| Trade function
//+------------------------------------------------------------------+
void OnTrade()
{
//--- check if a position is present and display the time of its changing
1204
Trade Functions
if(PositionSelect(_Symbol))
{
//--- receive position ID for further work
ulong position_ID=PositionGetInteger(POSITION_IDENTIFIER);
Print(_Symbol," position #",position_ID);
//--- receive the time of position forming in milliseconds since 01.01.1970
long create_time_msc=PositionGetInteger(POSITION_TIME_MSC);
PrintFormat("Position #%d
create_time_msc,TimeToString(create_time_msc/1000));
//--- receive the time of the position's last change in seconds since 01.01.1970
long update_time_sec=PositionGetInteger(POSITION_TIME_UPDATE);
PrintFormat("Position #%d
position_ID,update_time_sec,TimeToString(update_time_sec));
//--- receive the time of the position's last change in milliseconds since 01.01.1970
long update_time_msc=PositionGetInteger(POSITION_TIME_UPDATE_MSC);
PrintFormat("Position #%d
position_ID,update_time_msc,TimeToString(update_time_msc/1000));
}
//--}
See also
PositionGetSymbol(), PositionSelect(), Position Properties
1205
Trade Functions
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.
1. Immediately returns the property value.
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
);
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 the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
1206
Trade Functions
PositionGetTicket
The function returns the ticket of a position with the specified index in the list of open positions and
automatically selects the position to work with using functions PositionGetDouble, PositionGetInteger,
PositionGetString.
ulong PositionGetTicket(
int index
);
Parameters
index
[in] The index of a position in the list of open positions, numeration starts with 0.
Return Value
The ticket of the position. Returns 0 if the function fails.
Note
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right
before referring to them.
See also
PositionGetSymbol(), PositionSelect(), Position Properties
1207
Trade Functions
OrdersTotal
Returns the number of current orders.
int OrdersTotal();
Return Value
Value of the int type.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For 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
1208
Trade Functions
OrderGetTicket
Returns ticket of a corresponding order and automatically selects the order for further working with it
using functions.
ulong OrderGetTicket(
int index
);
Parameters
index
[in] Number of an order in the list of current orders.
Return Value
Value of the ulong type. If the function fails, 0 is returned.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For 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()
{
//--- 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;
total=OrdersTotal();
1209
Trade Functions
{
//--- return order properties
open_price
=OrderGetDouble(ORDER_PRICE_OPEN);
time_setup
=(datetime)OrderGetInteger(ORDER_TIME_SETUP);
symbol
=OrderGetString(ORDER_SYMBOL);
order_magic
=OrderGetInteger(ORDER_MAGIC);
positionID
=OrderGetInteger(ORDER_POSITION_ID);
initial_volume=OrderGetDouble(ORDER_VOLUME_INITIAL);
type
=EnumToString(ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE)));
// order ticket
type,
// type
initial_volume,
// placed volume
symbol,
// symbol
open_price,
See also
OrdersTotal(), OrderSelect(), OrderGetInteger()
1210
Trade Functions
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
Value of the bool type.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For 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
1211
Trade Functions
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.
1. Immediately returns the property value.
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
);
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
Value of the double type. If the function fails, 0 is returned.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For 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
1212
Trade Functions
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.
1. Immediately returns the property value.
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
);
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
Value of the long type. If the function fails, 0 is returned.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For 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
1213
Trade Functions
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.
1. Immediately returns the property value.
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
);
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
Value of the string type.
Note
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of
the "Toolbox" of the client terminal. For 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
1214
Trade Functions
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.
Return Value
It returns true if successful, otherwise returns false.
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;
1215
Trade Functions
for(uint i=0;i<total;i++)
{
//--- try to get deals ticket
if((ticket=HistoryDealGetTicket(i))>0)
{
//--- get deals properties
price =HistoryDealGetDouble(ticket,DEAL_PRICE);
time
=(datetime)HistoryDealGetInteger(ticket,DEAL_TIME);
symbol=HistoryDealGetString(ticket,DEAL_SYMBOL);
type
=HistoryDealGetInteger(ticket,DEAL_TYPE);
entry =HistoryDealGetInteger(ticket,DEAL_ENTRY);
profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
//--- only for current symbol
if(price && time && symbol==Symbol())
{
//--- create price object
name="TradeHistory_Deal_"+string(ticket);
if(entry) ObjectCreate(0,name,OBJ_ARROW_RIGHT_PRICE,0,time,price,0,0);
else
ObjectCreate(0,name,OBJ_ARROW_LEFT_PRICE,0,time,price,0,0);
See also
HistoryOrderSelect(), HistoryDealSelect()
1216
Trade Functions
HistorySelectByPosition
Retrieves the history of deals and orders having the specified position identifier.
bool HistorySelectByPosition(
long position_id
);
Parameters
position_id
[in] Position identifier that is set to every executed order and every deal.
Return Value
It returns true if successful, otherwise returns false.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
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
1217
Trade Functions
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
Returns true if successful, otherwise false.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
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
1218
Trade Functions
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
Value of the int type.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrderSelect(), HistoryOrderGetTicket(), Order Properties
1219
Trade Functions
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
);
Parameters
index
[in] Number of the order in the list of orders.
Return Value
Value of the ulong type. If the function fails, 0 is returned.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
Example:
void OnStart()
{
datetime from=0;
datetime to=TimeCurrent();
//--- request the entire history
HistorySelect(from,to);
//--- variables for returning values from order properties
ulong
ticket;
double
open_price;
double
initial_volume;
datetime time_setup;
datetime time_done;
string
symbol;
string
type;
long
order_magic;
long
positionID;
total=HistoryOrdersTotal();
1220
Trade Functions
open_price
=HistoryOrderGetDouble(ticket,ORDER_PRICE_OPEN);
time_setup
=(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_SETUP);
time_done
=(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE);
symbol
=HistoryOrderGetString(ticket,ORDER_SYMBOL);
order_magic
=HistoryOrderGetInteger(ticket,ORDER_MAGIC);
positionID
=HistoryOrderGetInteger(ticket,ORDER_POSITION_ID);
initial_volume=HistoryOrderGetDouble(ticket,ORDER_VOLUME_INITIAL);
type
=GetOrderType(HistoryOrderGetInteger(ticket,ORDER_TYPE));
// order ticket
type,
// type
initial_volume,
// placed volume
symbol,
// symbol
open_price,
);
}
}
//--}
//+------------------------------------------------------------------+
//| 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");
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
1221
Trade Functions
HistoryOrderGetDouble
Returns the requested order property. The order property must be of the double type. There are 2
variants of the function.
1. Immediately returns the property value.
double HistoryOrderGetDouble(
ulong
ticket_number,
ENUM_ORDER_PROPERTY_DOUBLE property_id
// Ticket
// 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
);
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
Value of the double type.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
1222
Trade Functions
HistoryOrderGetInteger
Returns the requested property of an order. The order property must be of datetime, int type. There
are 2 variants of the function.
1. Immediately returns the property value.
long HistoryOrderGetInteger(
ulong
ticket_number,
ENUM_ORDER_PROPERTY_INTEGER property_id
// Ticket
// 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
);
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
Value of the long type.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
Example:
//+------------------------------------------------------------------+
//| Trade function
//+------------------------------------------------------------------+
void OnTrade()
{
//--- receive the last order's ticket from week's trading history
ulong last_order=GetLastOrderTicket();
if(HistoryOrderSelect(last_order))
1223
Trade Functions
{
//--- time of placing an order in milliseconds since 01.01.1970
long time_setup_msc=HistoryOrderGetInteger(last_order,ORDER_TIME_SETUP_MSC);
PrintFormat("Order #%d ORDER_TIME_SETUP_MSC=%i64 => %s",
last_order,time_setup_msc,TimeToString(time_setup_msc/1000));
//--- order execution/cancellation time in milliseconds since 01.01.1970
long
time_done_msc=HistoryOrderGetInteger(last_order,ORDER_TIME_DONE_MSC);
//+------------------------------------------------------------------+
ulong GetLastOrderTicket()
{
//--- request history for the last 7 days
if(!GetTradeHistory(7))
{
//--- notify on unsuccessful call and return -1
Print(__FUNCTION__," HistorySelect() returned false");
return -1;
}
//--ulong first_order,last_order,orders=HistoryOrdersTotal();
//--- work with orders if there are any
if(orders>0)
{
Print("Orders = ",orders);
first_order=HistoryOrderGetTicket(0);
PrintFormat("first_order = %d",first_order);
if(orders>1)
{
last_order=HistoryOrderGetTicket((int)orders-1);
PrintFormat("last_order = %d",last_order);
return last_order;
}
return first_order;
}
//--- no order found, return -1
return -1;
}
//+--------------------------------------------------------------------------+
//| Requests history for the last days and returns false in case of failure
1224
Trade Functions
//+--------------------------------------------------------------------------+
bool GetTradeHistory(int days)
{
//--- set a week period to request trade history
datetime to=TimeCurrent();
datetime from=to-days*PeriodSeconds(PERIOD_D1);
ResetLastError();
//--- make a request and check the result
if(!HistorySelect(from,to))
{
Print(__FUNCTION__," HistorySelect=false. Error code=",GetLastError());
return false;
}
//--- history received successfully
return true;
}
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
1225
Trade Functions
HistoryOrderGetString
Returns the requested property of an order. The order property must be of the string type. There are 2
variants of the function.
1. Immediately returns the property value.
string HistoryOrderGetString(
ulong
ticket_number,
ENUM_ORDER_PROPERTY_STRING property_id
// Ticket
// 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
);
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
Value of the string type.
Note
Do not confuse orders of a trading history with current pending orders that appear on the "Trade"
tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of "Toolbox" of the client terminal.
See also
HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
1226
Trade Functions
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
Returns true if successful, otherwise false.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
HistoryDealSelect() clears in a mql5-program the list of deals available for reference, and copies the
single deal, if 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
1227
Trade Functions
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
Value of the int type.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealGetTicket(), Deal Properties
1228
Trade Functions
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
Value of the ulong type. If the function fails, 0 is returned.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:
void OnStart()
{
ulong deal_ticket;
// deal ticket
ulong order_ticket;
datetime transaction_time;
long deal_type ;
long position_ID;
// position ID
string deal_description;
// operation description
double volume;
// operation volume
string symbol;
//--- set the start and end date to request the history of deals
datetime from_date=0;
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);
1229
Trade Functions
position_ID=
HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID);
deal_description=
GetDealDescription(deal_type,volume,symbol,order_ticket,position_I
//+------------------------------------------------------------------+
string GetDealDescription(long deal_type,double volume,string symbol,long ticket,long pos_ID)
{
string descr;
//--switch(deal_type)
{
case DEAL_TYPE_BALANCE:
return ("balance");
case DEAL_TYPE_CREDIT:
return ("credit");
case DEAL_TYPE_CHARGE:
return ("charge");
case DEAL_TYPE_CORRECTION:
return ("correction");
case DEAL_TYPE_BUY:
descr="buy"; break;
case DEAL_TYPE_SELL:
descr="sell"; break;
case DEAL_TYPE_BONUS:
return ("bonus");
case DEAL_TYPE_COMMISSION:
case DEAL_TYPE_COMMISSION_DAILY:
case DEAL_TYPE_COMMISSION_MONTHLY:
case DEAL_TYPE_COMMISSION_AGENT_DAILY:
case DEAL_TYPE_BUY_CANCELED:
case DEAL_TYPE_SELL_CANCELED:
}
descr=StringFormat("%s %G %s (order #%d, position ID %d)",
descr,
// current description
);
return(descr);
//--}
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
1230
Trade Functions
HistoryDealGetDouble
Returns the requested property of a deal. The deal property must be of the double type. There are 2
variants of the function.
1. Immediately returns the property value.
double HistoryDealGetDouble(
ulong
ticket_number,
ENUM_DEAL_PROPERTY_DOUBLE property_id
// Ticket
// 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
);
Parameters
ticket_number
[in] Deal ticket.
property_id
[in]
Identifier of a deal property. The value can be one of the values
ENUM_DEAL_PROPERTY_DOUBLE enumeration.
of the
double_var
[out] Variable of the double type that accepts the value of the requested property.
Return Value
Value of the double type.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
See also
HistorySelect(), HistoryDealsTotal(), HistoryDealGetTicket(), Deal Properties
1231
Trade Functions
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.
1. Immediately returns the property value.
long HistoryDealGetInteger(
ulong
ticket_number,
ENUM_DEAL_PROPERTY_INTEGER property_id
// Ticket
// 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
);
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
Value of the long type.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:
//+------------------------------------------------------------------+
//| Trade function
//+------------------------------------------------------------------+
void OnTrade()
{
//--- receive the last deal's ticket from week's trading history
ulong last_deal=GetLastDealTicket();
if(HistoryDealSelect(last_deal))
{
1232
Trade Functions
//--- time of deal execution in milliseconds since 01.01.1970
long deal_time_msc=HistoryDealGetInteger(last_deal,DEAL_TIME_MSC);
PrintFormat("Deal #%d DEAL_TIME_MSC=%i64 => %s",
last_deal,deal_time_msc,TimeToString(deal_time_msc/1000));
}
else
PrintFormat("HistoryDealSelect() failed for #%d. Eror code=%d",
last_deal,GetLastError());
//--}
//+------------------------------------------------------------------+
//| Returns the last deal ticket in history or -1
//+------------------------------------------------------------------+
ulong GetLastDealTicket()
{
//--- request history for the last 7 days
if(!GetTradeHistory(7))
{
//--- notify on unsuccessful call and return -1
Print(__FUNCTION__," HistorySelect() returned false");
return -1;
}
//--ulong first_deal,last_deal,deals=HistoryOrdersTotal();
//--- work with orders if there are any
if(deals>0)
{
Print("Deals = ",deals);
first_deal=HistoryDealGetTicket(0);
PrintFormat("first_deal = %d",first_deal);
if(deals>1)
{
last_deal=HistoryDealGetTicket((int)deals-1);
PrintFormat("last_deal = %d",last_deal);
return last_deal;
}
return first_deal;
}
//--- no deal found, return -1
return -1;
}
//+--------------------------------------------------------------------------+
//| Requests history for the last days and returns false in case of failure
//+--------------------------------------------------------------------------+
bool GetTradeHistory(int days)
{
//--- set a week period to request trade history
datetime to=TimeCurrent();
datetime from=to-days*PeriodSeconds(PERIOD_D1);
1233
Trade Functions
ResetLastError();
//--- make a request and check the result
if(!HistorySelect(from,to))
{
Print(__FUNCTION__," HistorySelect=false. Error code=",GetLastError());
return false;
}
//--- history received successfully
return true;
}
See also
HistoryDealsTotal(), HistorySelect(), HistoryDealGetTicket(), Deal Properties
1234
Trade Functions
HistoryDealGetString
Returns the requested property of a deal. The deal property must be of the string type. There are 2
variants of the function.
1. Immediately returns the property value.
string HistoryDealGetString(
ulong
ticket_number,
ENUM_DEAL_PROPERTY_STRING property_id
// Ticket
// 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
);
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
Value of the string type.
Note
Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
See also
HistoryDealsTotal(), HistorySelect(), HistoryDealGetTicket(), Deal Properties
1235
Trade Signals
Trade Signals
This is the group of functions intended for managing trade signals. The functions allow:
get information about trade signals, available for copying,
get and set the signal copy settings,
subscribe and unsubscribe to the signal copying using MQL5 language functions.
Function
Action
SignalBaseGetDouble
SignalBaseGetInteger
SignalBaseGetString
SignalBaseSelect
SignalBaseTotal
SignalInfoGetDouble
SignalInfoGetInteger
SignalInfoGetString
SignalInfoSetDouble
SignalInfoSetInteger
SignalSubscribe
SignalUnsubscribe
Cancels subscription
1236
Trade Signals
SignalBaseGetDouble
Returns the value of double type property for selected signal.
double SignalBaseGetDouble(
ENUM_SIGNAL_BASE_DOUBLE
property_id,
// property identifier
);
Parameters
property_id
[in]
Signal property identifier. The
ENUM_SIGNAL_BASE_DOUBLE enumeration.
value
can
be
one
Return Value
The value of double type property of the selected signal.
of
the
values
of
the
1237
Trade Signals
SignalBaseGetInteger
Returns the value of integer type property for selected signal.
long SignalBaseGetInteger(
ENUM_SIGNAL_BASE_INTEGER
property_id,
// property identifier
);
Parameters
property_id
[in]
Signal property identifier. The
ENUM_SIGNAL_BASE_INTEGER enumeration.
value
can
be
one
Return Value
The value of integer type property of the selected signal.
of
the
values
of
the
1238
Trade Signals
SignalBaseGetString
Returns the value of string type property for selected signal.
string SignalBaseGetString(
ENUM_SIGNAL_BASE_STRING
property_id,
// property identifier
);
Parameters
property_id
[in]
Signal property identifier. The
ENUM_SIGNAL_BASE_STRING enumeration.
value
can
be
one
Return Value
The value of string type property of the selected signal.
of
the
values
of
the
1239
Trade Signals
SignalBaseSelect
Selects a signal from signals, available in terminal for further working with it.
bool SignalBaseSelect(
int
index
// signal index
);
Parameters
index
[in] Signal index in base of trading signals.
Return Value
Returns true if successful, otherwise returns false. To read more about the error call GetLastError().
Example:
void OnStart()
{
//--- get total amount of signals in the terminal
int total=SignalBaseTotal();
//--- process all signals
for(int i=0;i<total;i++)
{
//--- select the signal by index
if(SignalBaseSelect(i))
{
//--- get signal properties
long
id
=SignalBaseGetInteger(SIGNAL_BASE_ID);
// signal id
long
pips
=SignalBaseGetInteger(SIGNAL_BASE_PIPS);
// profit in pips
long
string name
=SignalBaseGetString(SIGNAL_BASE_NAME);
// signal name
// signal price
string curr
// signal currency
=SignalBaseGetString(SIGNAL_BASE_CURRENCY);
1240
Trade Signals
SignalBaseTotal
Returns the total amount of signals, available in terminal.
int SignalBaseTotal();
Return Value
The total amount of signals, available in terminal.
1241
Trade Signals
SignalInfoGetDouble
Returns the value of double type property of signal copy settings.
double SignalInfoGetDouble(
ENUM_SIGNAL_INFO_DOUBLE
property_id,
// property identifier
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_DOUBLE enumeration.
Return Value
The value of double type property of signal copy settings.
1242
Trade Signals
SignalInfoGetInteger
Returns the value of integer type property of signal copy settings.
long SignalInfoGetInteger(
ENUM_SIGNAL_INFO_INTEGER
property_id,
// property identifier
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_INTEGER enumeration.
Return Value
The value of integer type property of signal copy settings.
1243
Trade Signals
SignalInfoGetString
Returns the value of string type property of signal copy settings.
string SignalInfoGetString(
ENUM_SIGNAL_INFO_STRING
property_id,
// property identifier
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_STRING enumeration.
Return Value
The value of string type property of signal copy settings.
1244
Trade Signals
SignalInfoSetDouble
Sets the value of double type property of signal copy settings.
bool SignalInfoSetDouble(
ENUM_SIGNAL_INFO_DOUBLE
property_id,
// property identifier
double
value
// new value
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_DOUBLE enumeration.
value
[in] The value of signal copy settings property.
Return Value
Returns true if property has been changed, otherwise returns false. To read more about the error
call GetLastError().
1245
Trade Signals
SignalInfoSetInteger
Sets the value of integer type property of signal copy settings.
bool SignalInfoSetInteger(
ENUM_SIGNAL_INFO_INTEGER
property_id,
// property identifier
long
value
// new value
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_INTEGER enumeration.
value
[in] The value of signal copy settings property.
Return Value
Returns true if property has been changed, otherwise returns false. To read more about the error
call GetLastError().
1246
Trade Signals
SignalSubscribe
Subscribes to the trading signal.
bool SignalSubscribe(
long
signal_id
// signal id
);
Parameters
signal_id
[in] Signal identifier.
Return Value
Returns true if subscription was successful, otherwise returns false. To read more about the error
call GetLastError().
1247
Trade Signals
SignalUnsubscribe
Cancels subscription.
bool SignalUnsubscribe();
Return Value
Returns true if subscription has been canceled successfully, otherwise returns false. To read more
about the error call GetLastError().
1248
Action
GlobalVariableCheck
GlobalVariableTime
GlobalVariableDel
GlobalVariableGet
GlobalVariableName
GlobalVariableSet
GlobalVariablesFlush
GlobalVariableTemp
GlobalVariableSetOnCondition
GlobalVariablesDeleteAll
GlobalVariablesTotal
1249
GlobalVariableCheck
Checks the existence of a global variable with the specified name
bool GlobalVariableCheck(
string name
);
Parameters
name
[in] Global variable name.
Return Value
Returns true, if the global variable exists, otherwise returns false.
Global variables exist in the client terminal during 4 weeks since their last use, then they are
automatically deleted.
See also
GlobalVariableTime()
1250
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. Addressing a variable for
its value, for example using the GlobalVariableGet() and GlobalVariableCheck() functions, also
modifies the time of last access. 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 automatically deleted.
See also
GlobalVariableCheck()
1251
GlobalVariableDel
Deletes a global variable from the client terminal.
bool GlobalVariableDel(
string 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.
1252
GlobalVariableGet
Returns the value of an existing global variable of the client terminal. There are 2 variants of the
function.
1. Immediately returns the value of the global variable.
double GlobalVariableGet(
string name
);
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,
double&double_var
);
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.
1253
GlobalVariableName
Returns the name of a global variable by its ordinal number.
string GlobalVariableName(
int index
);
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 its 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.
1254
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,
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
A global variable name should not exceed 63 characters. Global variables exist in the client terminal
during 4 weeks since their last use, then they are automatically deleted.
1255
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.
1256
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
);
Parameters
name
[in] The name of a temporary global variable.
Return Value
If successful, the function returns true, otherwise - false. To get details about the error, you should
call the GetLastError() function.
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.
1257
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,
double value,
double check_value
);
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.
1258
GlobalVariablesDeleteAll
Deletes global variables of the client terminal.
int GlobalVariablesDeleteAll(
string
prefix_name=NULL,
datetime limit_data=0
);
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
The number of deleted variables.
Note
If both options are equal to zero (prefix_name = NULL and limit_data = 0), then function deletes all
global variables of the terminal. If both parameters 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.
1259
GlobalVariablesTotal
Returns the total number of global variables of the client terminal.
int GlobalVariablesTotal();
Return Value
Number of global variables.
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.
1260
File Functions
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_data_folder\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:
Action
FileFindFirst
FileFindNext
FileFindClose
FileOpen
FileDelete
FileFlush
FileGetInteger
FileIsEnding
FileIsLineEnding
FileClose
FileIsExist
FileCopy
started
by
the
1261
File Functions
FileReadArray
FileReadBool
FileReadDatetime
FileReadDouble
FileReadFloat
FileReadInteger
FileReadLong
FileReadNumber
FileReadString
FileReadStruct
FileSeek
FileSize
FileTell
FileWrite
FileWriteArray
FileWriteDouble
1262
File Functions
FileWriteFloat
FileWriteInteger
FileWriteLong
FileWriteString
FileWriteStruct
FolderCreate
FolderDelete
FolderClean
If the file is opened for writing using FileOpen(), all subfolders specified in the path will be created if
there are no such ones.
1263
File Functions
FileFindFirst
The function starts the search of files or subdirectories in a directory in accordance with the specified
filter.
long FileFindFirst(
const string
file_filter,
string&
returned_filename,
int
common_flag=0
);
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 or
subdirectory is placed. Only the file name is returned (including the extension), the directories and
subdirectories are not included no matter if they are specified or not in the search filter.
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 \Terminal\Common\Files. 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 and
subdirectories by the FileFindNext() function, or INVALID_HANDLE when there is no file and
subdirectory corresponding to the filter (in the particular case - when the directory is empty). After
searching, the 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:
1264
File Functions
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="Dir1\\*";
//+------------------------------------------------------------------+
//| Script program start function
|
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
string int_dir="";
int
i=1,pos=0,last_pos=-1;
//--- search for the last backslash
while(!IsStopped())
{
pos=StringFind(InpFilter,"\\",pos+1);
if(pos>=0)
last_pos=pos;
else
break;
}
//--- the filter contains the folder name
if(last_pos>=0)
int_dir=StringSubstr(InpFilter,0,last_pos+1);
//--- get the search handle in the root of the local folder
long search_handle=FileFindFirst(InpFilter,file_name);
//--- check if the FileFindFirst() is executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- in a loop, check if the passed strings are the names of files or directories
do
{
ResetLastError();
//--- if it's a file, the function returns true, and if it's a directory, it returns error
FileIsExist(int_dir+file_name);
PrintFormat("%d : %s name = %s",i,GetLastError()==ERR_FILE_IS_DIRECTORY ? "Directory" : "F
i++;
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
See also
FileFindNext, FileFindClose
1265
File Functions
FileFindNext
The function continues the search started by FileFindFirst().
bool FileFindNext(
long
search_handle,
// Search handle
string&
returned_filename
);
Parameters
search_handle
[in] Search handle, retrieved by FileFindFirst().
returned_filename
[out] The name of the next file or subdirectory found. Only the file name is returned (including the
extension), the directories and subdirectories are not included no matter if they are specified or
not in the search filter.
Return Value
If successful returns true, otherwise false.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="*";
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
int
i=1;
//--- if this is a file, the function will return true, if it is a directory, the function
FileIsExist(file_name);
1266
File Functions
//--- close search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
See also
FileFindFirst, FileFindClose
1267
File Functions
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
Function must be called to free up system resources.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="*";
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
int
i=1;
//--- if this is a file, the function will return true, if it is a directory, the function
FileIsExist(file_name);
PrintFormat("%d : %s name = %s",i,GetLastError()==5018 ? "Directory" : "File",file_name);
i++;
}
while(FileFindNext(search_handle,file_name));
//--- close search handle
FileFindClose(search_handle);
}
1268
File Functions
else
Print("Files not found!");
}
See also
FileFindFirst, FileFindNext
1269
File Functions
FileIsExist
Checks the existence of a file.
bool FileIsExist(
const string file_name,
// File name
int
// Search area
common_flag=0
);
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 \Terminal\Common\Files. Otherwise, the file is
located in a local folder.
Return Value
Returns true, if the specified file exists.
Note
Checked file can turn out to be a subdirectory. In this case, FileIsExist() function will return false,
while error 5018 will be logged in _LastError variable - "This is a directory, not a file" (see example
for FileFindFirst function).
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 \Terminal\Common\Files, otherwise the function looks for a file in a local folder (MQL5
\Files or MQL5\Tester\Files in the case of testing).
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- date for old files
input datetime InpFilesDate=D'2013.01.01 00:00';
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string
file_name;
string
datetime create_date;
string
files[];
int
def_size=25;
int
size=0;
// number of files
1270
File Functions
//--- allocate memory for the array
ArrayResize(files,def_size);
//--- receive the search handle in the local folder's root
long search_handle=FileFindFirst(filter,file_name);
//--- check if FileFindFirst() executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- searching files in the loop
do
{
files[size]=file_name;
//--- increase the array size
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//--- reset the error value
ResetLastError();
//--- receive the file creation date
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//--- check if the file is old
if(create_date<InpFilesDate)
{
PrintFormat("%s file deleted!",file_name);
//--- delete the old file
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
{
Print("Files not found!");
return;
}
//--- check what files have remained
PrintFormat("Results:");
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat("%s file exists!",files[i]);
else
PrintFormat("%s file deleted!",files[i]);
}
}
1271
File Functions
See also
FileFindFirst
1272
File Functions
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 \Terminal\Common
\Files
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,
1273
File Functions
the file is opened in a shared folder for all MetaTrader 5 client terminals.
"Named pipes" can be opened according to the following rules:
Pipe name is a string, which should have the following look: "\\servername\pipe\pipename", where
servername - server name in the network, while pipename is a pipe name. If the pipes are used on
the same computer, the server name can be omitted but a point should be inserted instead of it: "\
\.\pipe\pipename". A client trying to connect the pipe should know its name.
FileFlush() and FileSeek() should be called to the beginning of a file between sequential operations
//+------------------------------------------------------------------+
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());
}
//--- correct way of working in the "file sandbox"
ResetLastError();
filehandle=FileOpen("fractals.csv",FILE_WRITE|FILE_CSV);
if(filehandle!=INVALID_HANDLE)
{
FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(_Period));
FileClose(filehandle);
Print("FileOpen OK");
}
else Print("Operation FileOpen failed, error ",GetLastError());
//--- another example with the creation of an enclosed directory in MQL5\Files\
string subfolder="Research";
filehandle=FileOpen(subfolder+"\\fractals.txt",FILE_WRITE|FILE_CSV);
if(filehandle!=INVALID_HANDLE)
{
FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(_Period));
FileClose(filehandle);
1274
File Functions
Print("The file must be created in the folder "+terminal_data_path+"\\"+subfolder);
}
else Print("File open failed, error ",GetLastError());
}
See also
Use of a Codepage, FileFindFirst, FolderCreate, File opening flags
1275
File Functions
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.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt";
// file name
// directory name
input int
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the path to the file we are going to use
PrintFormat("Working %s\\Files\\ folder",TerminalInfoString(TERMINAL_DATA_PATH));
//--- reset the error value
ResetLastError();
//--- open the file for reading (if the file does not exist, the error will occur)
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//--- print the file contents
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
}
1276
File Functions
FileCopy
The function copies the original file from a local or shared folder to another file.
bool FileCopy(
const string src_file_name,
int
// Location
common_flag,
int
// Access mode
mode_flags
);
Parameters
src_file_name
[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 \Terminal\Common\Files. Otherwise, the file is
located in a local folder (for example, common_flag=0).
dst_file_name
[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
In case of failure the function returns false.
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.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpSrc="source.txt";
// source
// copy
input int
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
1277
File Functions
{
//--- display the source contents (it must exist)
if(!FileDisplay(InpSrc))
return;
//--- check if the copy file already exists (may not be created)
if(!FileDisplay(InpDst))
{
//--- the copy file does not exist, copying without FILE_REWRITE flag (correct copying)
if(FileCopy(InpSrc,0,InpDst,0))
Print("File is copied!");
else
Print("File is not copied!");
}
else
{
//--- the copy file already exists, try to copy without FILE_REWRITE flag (incorrect copying)
if(FileCopy(InpSrc,0,InpDst,0))
Print("File is copied!");
else
Print("File is not copied!");
//--- InpDst file's contents remains the same
FileDisplay(InpDst);
//--- copy once more with FILE_REWRITE flag (correct copying if the file exists)
if(FileCopy(InpSrc,0,InpDst,FILE_REWRITE))
Print("File is copied!");
else
Print("File is not copied!");
}
//--- receive InpSrc file copy
FileDisplay(InpDst);
}
//+------------------------------------------------------------------+
//| Read the file contents
//+------------------------------------------------------------------+
bool FileDisplay(const string file_name)
{
//--- reset the error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(file_name,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//--- display the file contents in the loop
Print("+---------------------+");
PrintFormat("File name = %s",file_name);
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
Print("+---------------------+");
//--- close the file
1278
File Functions
FileClose(file_handle);
return(true);
}
//--- failed to open the file
PrintFormat("%s is not opened, error = %d",file_name,GetLastError());
return(false);
}
1279
File Functions
FileDelete
Deletes the specified file in a local folder of the client terminal.
bool FileDelete(
const string file_name,
int
);
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 \Terminal\Common\Files. Otherwise, the file is located in a
local folder.
Return Value
In case of failure the function returns false.
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 \Terminal\Common\Files.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- date for old files
input datetime InpFilesDate=D'2013.01.01 00:00';
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string
file_name;
string
datetime create_date;
string
files[];
int
def_size=25;
int
size=0;
// number of files
1280
File Functions
//--- check if FileFindFirst() executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- searching files in the loop
do
{
files[size]=file_name;
//--- increase the array size
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//--- reset the error value
ResetLastError();
//--- receive the file creation date
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//--- check if the file is old
if(create_date<InpFilesDate)
{
PrintFormat("%s file deleted!",file_name);
//--- delete the old file
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
{
Print("Files not found!");
return;
}
//--- check what files have remained
PrintFormat("Results:");
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat("%s file exists!",files[i]);
else
PrintFormat("%s file deleted!",files[i]);
}
}
1281
File Functions
FileMove
Moves a file from a local or shared folder to another folder.
bool FileMove(
const string src_file_name,
int
// Location
common_flag,
int
// Access mode
mode_flags
);
Parameters
src_file_name
[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 \Terminal\Common\Files. Otherwise, the file is
located in a local folder (common_flag=0).
dst_file_name
[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
In case of failure the function returns false.
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.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpSrcName="data.txt";
input string InpDstName="newdata.txt";
input string InpSrcDirectory="SomeFolder";
input string InpDstDirectory="OtherFolder";
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
1282
File Functions
void OnStart()
{
string local=TerminalInfoString(TERMINAL_DATA_PATH);
string common=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
//--- receive file paths
string src_path;
string dst_path;
StringConcatenate(src_path,InpSrcDirectory,"//",InpSrcName);
StringConcatenate(dst_path,InpDstDirectory,"//",InpDstName);
//--- check if the source file exists (if not - exit)
if(FileIsExist(src_path))
PrintFormat("%s file exists in the %s\\Files\\%s folder",InpSrcName,local,InpSrcDirectory);
else
{
PrintFormat("Error, %s source file not found",InpSrcName);
return;
}
//--- check if the result file already exists
if(FileIsExist(dst_path,FILE_COMMON))
{
PrintFormat("%s file exists in the %s\\Files\\%s folder",InpDstName,common,InpDstDirectory);
//--- file exists, moving should be performed with FILE_REWRITE flag
ResetLastError();
if(FileMove(src_path,0,dst_path,FILE_COMMON|FILE_REWRITE))
PrintFormat("%s file moved",InpSrcName);
else
PrintFormat("Error! Code = %d",GetLastError());
}
else
{
See also
FileIsExist
1283
File Functions
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
When writing to a file, the data may be actually found there only after some time. To save the data
in the file instantly, use FileFlush() function. If the function is not used, part of the data that has
not been stored in the disk yet, will be forcibly written there only when the file is closed using
FileClose() function.
The function should be used when written data is of a certain value. It should be kept in mind that
frequent function call may affect the program operation speed.
Function FileFlush () must be called between the operations of reading from a file and writing to it.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- file name for writing
input string InpFileName="example.csv"; // file name
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- reset error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(InpFileName,FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
//--- write data to the file
for(int i=0;i<1000;i++)
{
//--- call write function
FileWrite(file_handle,TimeCurrent(),SymbolInfoDouble(Symbol(),SYMBOL_BID),SymbolInfoDouble
//--- save data on the disk at each 128th iteration
if((i & 127)==127)
1284
File Functions
{
//--- now, data will be located in the file and will not be lost in case of a critical
FileFlush(file_handle);
PrintFormat("i = %d, OK",i);
}
//--- 0.01 second pause
Sleep(10);
}
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
}
See also
FileClose
1285
File Functions
FileGetInteger
Gets an integer property of a file. There are two variants of the function.
1. Get a property by the handle of a file.
long FileGetInteger(
int
file_handle,
ENUM_FILE_PROPERTY_INTEGER property_id
// File handle
// Property ID
);
file_name,
// File name
ENUM_FILE_PROPERTY_INTEGER property_id,
// Property ID
bool
common_folder=false
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
file_name
[in] File name.
property_id
[in] File property ID. The value can be one of the values of the ENUM_FILE_PROPERTY_INTEGER
enumeration. If the second variant of the function is used, you can receive only the values of the
following properties: FILE_EXISTS, FILE_CREATE_DATE, FILE_MODIFY_DATE, FILE_ACCESS_DATE
and FILE_SIZE.
common_folder=false
[in] Points to the file location. If the parameter is false, terminal data folder is viewed. Otherwise
it is assumed that the file is in the shared folder of all terminals \Terminal\Common\Files
(FILE_COMMON).
Return Value
The value of the property. In case of an error, -1 is returned. To get an error code use the
GetLastError() function.
If a folder is specified when getting properties by the name, the function will have error 5018
(ERR_MQL_FILE_IS_DIRECTORY) in any case, though the return value will be correct.
Note
The function always changes the error code. In case of successful completion the error code is reset
to NULL.
Example:
//--- display the window of input parameters when launching the script
1286
File Functions
#property script_show_inputs
//--- input parameters
input string InpFileName="data.csv";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string path=InpDirectoryName+"//"+InpFileName;
long
l=0;
//+------------------------------------------------------------------+
void FileInfo(const int handle,const ENUM_FILE_PROPERTY_INTEGER id,
long l,const string type)
{
//--- receive the property value
ResetLastError();
if((l=FileGetInteger(handle,id))!=-1)
{
//--- the value received, display it in the correct format
1287
File Functions
if(!StringCompare(type,"bool"))
Print(EnumToString(id)," = ",l ? "true" : "false");
if(!StringCompare(type,"date"))
Print(EnumToString(id)," = ",(datetime)l);
if(!StringCompare(type,"other"))
Print(EnumToString(id)," = ",l);
}
else
Print("Error, Code = ",GetLastError());
}
See also
File Operations, File Properties
1288
File Functions
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.
Note
To define the end of the file, the function tries to read the next string from it. If the string does not
exist, the function returns true, otherwise it returns false.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt";
// file name
// directory name
input int
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the path to the file we are going to use
PrintFormat("Working %s\\Files\\ folder",TerminalInfoString(TERMINAL_DATA_PATH));
//--- reset the error value
ResetLastError();
//--- open the file for reading (if the file does not exist, the error will occur)
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//--- print the file contents
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
1289
File Functions
}
1290
File Functions
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).
Example (the file obtained during the execution of an example for FileWriteString function is used
here)
//+------------------------------------------------------------------+
//|
Demo_FileIsLineEnding.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots
#property indicator_type1
DRAW_COLOR_BARS
#property indicator_color1
clrRed, clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
// file name
open_buff[];
double
high_buff[];
double
low_buff[];
double
close_buff[];
double
color_buff[];
ovb_ind=0;
int
ovb_size=0;
datetime ovb_time[];
1291
File Functions
//--- oversold variables
int
ovs_ind=0;
int
ovs_size=0;
datetime ovs_time[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- variables of array sizes by default
int ovb_def_size=100;
int ovs_def_size=100;
//--- allocate memory for arrays
ArrayResize(ovb_time,ovb_def_size);
ArrayResize(ovs_time,ovs_def_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
double value;
//--- read data from file
while(!FileIsEnding(file_handle))
{
//--- read the first value in the string
value=FileReadNumber(file_handle);
//--- read to different arrays according to the function result
if(value>=70)
ReadData(file_handle,ovb_time,ovb_size,ovb_def_size);
else
ReadData(file_handle,ovs_time,ovs_size,ovs_def_size);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,open_buff,INDICATOR_DATA);
SetIndexBuffer(1,high_buff,INDICATOR_DATA);
SetIndexBuffer(2,low_buff,INDICATOR_DATA);
SetIndexBuffer(3,close_buff,INDICATOR_DATA);
SetIndexBuffer(4,color_buff,INDICATOR_COLOR_INDEX);
1292
File Functions
//---- set the indicator values that will not be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Read the file's string data
//+------------------------------------------------------------------+
void ReadData(const int file_handle,datetime &arr[],int &size,int &def_size)
{
bool flag=false;
//--- read till the end of the string or of the file is reached
while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
{
//--- shift the position by reading the number
if(flag)
FileReadNumber(file_handle);
//--- store the current date
arr[size]=FileReadDatetime(file_handle);
size++;
//--- increase the array size if necessary
if(size==def_size)
{
def_size+=100;
ArrayResize(arr,def_size);
}
//--- slip past the first iteration
flag=true;
}
}
//+------------------------------------------------------------------+
//| 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[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
1293
File Functions
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
open_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
close_buff[i]=0;
color_buff[i]=0;
//--- check if any data is still present
if(ovb_ind<ovb_size)
for(int j=ovb_ind;j<ovb_size;j++)
{
//--- if the dates coincide, the bar is in the overbought area
if(time[i]==ovb_time[j])
{
open_buff[i]=open[i];
high_buff[i]=high[i];
low_buff[i]=low[i];
close_buff[i]=close[i];
//--- 0 - red color
color_buff[i]=0;
//--- increase the counter
ovb_ind=j+1;
break;
}
}
//--- check if any data still exists
if(ovs_ind<ovs_size)
for(int j=ovs_ind;j<ovs_size;j++)
{
//--- if the dates coincide, the bar is in the oversold area
if(time[i]==ovs_time[j])
{
open_buff[i]=open[i];
high_buff[i]=high[i];
low_buff[i]=low[i];
close_buff[i]=close[i];
//--- 1 - blue color
color_buff[i]=1;
//--- increase the counter
ovs_ind=j+1;
break;
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
1294
File Functions
//+------------------------------------------------------------------+
//| ChartEvent event handler
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//--- change the indicator width according to the scale
if(ChartGetInteger(0,CHART_SCALE)>3)
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
else
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
}
See also
FileWriteString
1295
File Functions
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=0,
int
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=0
[in] Start position to read from the array.
count=WHOLE_ARRAY
[in] Number of elements to read. By default, reads the entire array (count=WHOLE_ARRAY).
Return Value
Number of elements read.
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.
Example (the file obtained after execution of the example for FileWriteArray function is used here)
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="data.bin";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| Structure for storing price data
//+------------------------------------------------------------------+
struct prices
{
datetime
date; // date
double
bid;
// bid price
double
ask;
// ask price
};
//+------------------------------------------------------------------+
//| Script program start function
1296
File Functions
//+------------------------------------------------------------------+
void OnStart()
{
//--- structure array
prices arr[];
//--- file path
string path=InpDirectoryName+"//"+InpFileName;
//--- open the file
ResetLastError();
int file_handle=FileOpen(path,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
//--- read all data from the file to the array
FileReadArray(file_handle,arr);
//--- receive the array size
int size=ArraySize(arr);
//--- print data from the array
for(int i=0;i<size;i++)
Print("Date = ",arr[i].date," Bid = ",arr[i].bid," Ask = ",arr[i].ask);
Print("Total data = ",size);
//--- close the file
FileClose(file_handle);
}
else
Print("File open failed, error ",GetLastError());
}
See also
Variables, FileWriteArray
1297
File Functions
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.
Example (the file obtained after executing the example for FileWrite function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadBool.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"UpSignal"
#property indicator_type1
DRAW_ARROW
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"DownSignal"
#property indicator_type2
DRAW_ARROW
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
// file name
ind=0;
// index
double
upbuff[];
double
downbuff[];
1298
File Functions
bool
size=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for reading",InpFileName);
//--- first, read the number of signals
size=(int)FileReadNumber(file_handle);
//--- allocate memory for the arrays
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
//--- signal time
time_buff[i]=FileReadDatetime(file_handle);
//--- signal value
sign_buff[i]=FileReadBool(file_handle);
}
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//--- set the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//---- set the indicator values that will not be seen on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
1299
File Functions
//+------------------------------------------------------------------+
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[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(high,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
upbuff[i]=0;
downbuff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, use the value from the file
if(time[i]==time_buff[j])
{
//--- draw the arrow according to the signal
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Type bool, FileWrite
1300
File Functions
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
The value of datetime type.
Example (the file obtained after executing the example for FileWrite function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadDateTime.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"UpSignal"
#property indicator_type1
DRAW_ARROW
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"DownSignal"
#property indicator_type2
DRAW_ARROW
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
// file name
ind=0;
// index
double
upbuff[];
double
downbuff[];
bool
1301
File Functions
datetime time_buff[]; // array of signals' arrival time
int
size=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for reading",InpFileName);
//--- first, read the number of signals
size=(int)FileReadNumber(file_handle);
//--- allocate memory for the arrays
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
//--- signal time
time_buff[i]=FileReadDatetime(file_handle);
//--- signal value
sign_buff[i]=FileReadBool(file_handle);
}
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//--- set the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//---- set the indicator values that will not be seen on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
1302
File Functions
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[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(high,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
upbuff[i]=0;
downbuff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, use the value from the file
if(time[i]==time_buff[j])
{
//--- draw the arrow according to the signal
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Type datetime, StringToTime, TimeToString, FileWrite
1303
File Functions
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
The value of double type.
Note
For more details about the error, call GetLastError().
Example (the file obtained after executing the example for FileWriteDouble function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadDouble.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"MA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
#property indicator_separate_window
//--- data reading parameters
input string InpFileName="MA.csv";
// file name
ind=0;
int
size=0;
double
ma_buff[];
datetime time_buff[];
//--- indicator buffer
double
buff[];
//+------------------------------------------------------------------+
1304
File Functions
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, read the amount of data in the file
size=(int)FileReadDouble(file_handle);
//--- allocate memory for the arrays
ArrayResize(ma_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadDouble(file_handle);
ma_buff[i]=FileReadDouble(file_handle);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer with index 0
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will not be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
1305
File Functions
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
//--- check if any data still exists
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if the dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
buff[i]=ma_buff[j];
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Real types (double, float), StringToDouble, DoubleToString, FileWriteDouble
1306
File Functions
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
The value of float type.
Note
For more details about the error, call GetLastError().
Example (the file obtained after executing the example for FileWriteFloat function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadFloat.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"CloseLine"
#property indicator_type1
DRAW_COLOR_LINE
#property indicator_color1
clrRed,clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
ind=0;
int
size=0;
double
close_buff[];
datetime time_buff[];
//--- indicator buffers
double
buff[];
double
color_buff[];
//+------------------------------------------------------------------+
1307
File Functions
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
int def_size=100;
//--- allocate memory for the arrays
ArrayResize(close_buff,def_size);
ArrayResize(time_buff,def_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- read time and price values
time_buff[size]=(datetime)FileReadDouble(file_handle);
close_buff[size]=(double)FileReadFloat(file_handle);
size++;
//--- increase the array sizes if they are overflown
if(size==def_size)
{
def_size+=100;
ArrayResize(close_buff,def_size);
ArrayResize(time_buff,def_size);
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- bind the arrays to the indicator buffers
SetIndexBuffer(0,buff,INDICATOR_DATA);
SetIndexBuffer(1,color_buff,INDICATOR_COLOR_INDEX);
//---- set the indicator values that will not be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
1308
File Functions
//+------------------------------------------------------------------+
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[])
{
ArraySetAsSeries(time,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
color_buff[i]=0; // red color by default
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if the dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
//--- receive the price
buff[i]=close_buff[j];
//--- if the current price exceeds the previous one, the color is blue
if(buff[i-1]>buff[i])
color_buff[i]=1;
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Real types (double, float), FileReadDouble, FileWriteFloat
1309
File Functions
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
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
size=INT_VALUE
[in] Number of bytes (up to 4 inclusive) that should be read. 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
A value of the int type. The result of this function must be explicitly cast to a target type, i.e. to the
type of data that you need to read. Since a value of the int type is returned, it can be easily
converted to any integer value. The file pointer is shifted by the number of bytes read.
Note
When reading less than 4 bytes, the received result is always positive. If one or two bytes are read,
the sign of the number can be determined by explicit casting to type char (1 byte) or short (2 bytes).
Getting the sign for a three-byte number is not trivial, since there is no corresponding underlying
type.
Example (the file obtained after executing the example for FileWriteInteger function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadInteger.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Trends"
#property indicator_type1
DRAW_SECTION
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
1310
File Functions
//--- parameters for data reading
input string InpFileName="Trend.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//--- global variables
int
ind=0;
int
size=0;
datetime time_buff[];
//--- indicator buffers
double
buff[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
int def_size=100;
//--- allocate memory for the array
ArrayResize(time_buff,def_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- additional variables
int
arr_size;
uchar
arr[];
1311
File Functions
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will not be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(close,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
//--- receive the price
buff[i]=close[i];
//--- increase the counter
ind=j+1;
break;
}
}
}
1312
File Functions
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
IntegerToString, StringToInteger, Integer types, FileWriteInteger
1313
File Functions
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
The value of long type.
Example (the file obtained during the execution of an example for FileWriteLong function is used
here)
//+------------------------------------------------------------------+
//|
Demo_FileReadLong.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_buffers 1
#property indicator_plots
"Volume"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrYellow
#property indicator_style1
STYLE_SOLID
#property indicator_width1
#property indicator_separate_window
//--- parameters for data reading
input string InpFileName="Volume.bin"; // file name
input string InpDirectoryName="Data";
// directory name
ind=0;
int
size=0;
long
volume_buff[];
datetime time_buff[];
//--- indicator buffers
double
buff[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
1314
File Functions
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, read the amount of data in the file
size=(int)FileReadLong(file_handle);
//--- allocate memory for the arrays
ArrayResize(volume_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadLong(file_handle);
volume_buff[i]=FileReadLong(file_handle);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer with 0 index
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
1315
File Functions
ArraySetAsSeries(time,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
buff[i]=(double)volume_buff[j];
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Integer types, FileReadInteger, FileWriteLong
1316
File Functions
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
The value of double type.
Example (the file obtained during the execution of an example for FileWriteString function is used
here)
//+------------------------------------------------------------------+
//|
Demo_FileReadNumber.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots
#property indicator_type1
DRAW_COLOR_BARS
#property indicator_color1
clrRed, clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
// file name
open_buff[];
double
high_buff[];
double
low_buff[];
double
close_buff[];
double
color_buff[];
ovb_ind=0;
int
ovb_size=0;
datetime ovb_time[];
1317
File Functions
//--- oversold variables
int
ovs_ind=0;
int
ovs_size=0;
datetime ovs_time[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- variables of array sizes by default
int ovb_def_size=100;
int ovs_def_size=100;
//--- allocate memory for arrays
ArrayResize(ovb_time,ovb_def_size);
ArrayResize(ovs_time,ovs_def_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
double value;
//--- read data from file
while(!FileIsEnding(file_handle))
{
//--- read the first value in the string
value=FileReadNumber(file_handle);
//--- read to different arrays according to the function result
if(value>=70)
ReadData(file_handle,ovb_time,ovb_size,ovb_def_size);
else
ReadData(file_handle,ovs_time,ovs_size,ovs_def_size);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,open_buff,INDICATOR_DATA);
SetIndexBuffer(1,high_buff,INDICATOR_DATA);
SetIndexBuffer(2,low_buff,INDICATOR_DATA);
SetIndexBuffer(3,close_buff,INDICATOR_DATA);
SetIndexBuffer(4,color_buff,INDICATOR_COLOR_INDEX);
1318
File Functions
//---- set the indicator values that will not be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Read the file's string data
//+------------------------------------------------------------------+
void ReadData(const int file_handle,datetime &arr[],int &size,int &def_size)
{
bool flag=false;
//--- read till the end of the string or of the file is reached
while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
{
//--- shift the carriage after reading the number
if(flag)
FileReadNumber(file_handle);
//--- store the current date
arr[size]=FileReadDatetime(file_handle);
size++;
//--- increase the array size if necessary
if(size==def_size)
{
def_size+=100;
ArrayResize(arr,def_size);
}
//--- slip past the first iteration
flag=true;
}
}
//+------------------------------------------------------------------+
//| 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[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
1319
File Functions
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
open_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
close_buff[i]=0;
color_buff[i]=0;
//--- check if any date is still present
if(ovb_ind<ovb_size)
for(int j=ovb_ind;j<ovb_size;j++)
{
//--- if the dates coincide, the bar is in the overbought area
if(time[i]==ovb_time[j])
{
open_buff[i]=open[i];
high_buff[i]=high[i];
low_buff[i]=low[i];
close_buff[i]=close[i];
//--- 0 - red color
color_buff[i]=0;
//--- increase the counter
ovb_ind=j+1;
break;
}
}
//--- check if any data still exists
if(ovs_ind<ovs_size)
for(int j=ovs_ind;j<ovs_size;j++)
{
//--- if the dates coincide, the bar is in the oversold area
if(time[i]==ovs_time[j])
{
open_buff[i]=open[i];
high_buff[i]=high[i];
low_buff[i]=low[i];
close_buff[i]=close[i];
//--- 1 - blue color
color_buff[i]=1;
//--- increase the counter
ovs_ind=j+1;
break;
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
1320
File Functions
//+------------------------------------------------------------------+
//| ChartEvent event handler
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//--- change the indicator width according to the scale
if(ChartGetInteger(0,CHART_SCALE)>3)
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
else
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
}
See also
FileWriteString
1321
File Functions
FileReadString
The function reads a string from the current position of a file pointer in a file.
string FileReadString(
int file_handle,
// File handle
int length=-1
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
length=-1
[in] Number of characters to read.
Return Value
Line read (string).
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.
Example (the file obtained after executing the example for FileWriteInteger function is used here)
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for data reading
input string InpFileName="Trend.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- additional variables
int
str_size;
string str;
1322
File Functions
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- find out how many symbols are used for writing the time
str_size=FileReadInteger(file_handle,INT_VALUE);
//--- read the string
str=FileReadString(file_handle,str_size);
//--- print the string
PrintFormat(str);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
String Type, Conversion Functions, FileWriteInteger
1323
File Functions
FileReadStruct
The function reads contents into a structure passed as a parameter from a binary-file, starting with
the current position of the file pointer.
uint FileReadStruct(
int
file_handle,
// file handle
int
size=-1
);
Parameters
file_handle
[in] File descriptor of an open bin-file.
struct_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.
Example (the file obtained after using the example for FileWriteStruct function is used here)
//+------------------------------------------------------------------+
//|
Demo_FileReadStruct.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots
"Candles"
#property indicator_type1
DRAW_CANDLES
#property indicator_color1
clrOrange
#property indicator_style1
STYLE_SOLID
#property indicator_width1
#property indicator_separate_window
//--- parameters for receiving data
input string
input string
InpDirectoryName="Data";
// directory name
1324
File Functions
//+------------------------------------------------------------------+
//| Structure for storing candlestick data
//+------------------------------------------------------------------+
struct candlesticks
{
double
open;
double
// open price
double
high;
// high price
double
low;
// low price
datetime
date;
// date
};
//--- indicator buffers
double
open_buff[];
double
close_buff[];
double
high_buff[];
double
low_buff[];
size=0;
int
ind=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
int default_size=100;
ArrayResize(cand_buff,default_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- write data to the array
FileReadStruct(file_handle,cand_buff[size]);
size++;
//--- check if the array is overflown
if(size==default_size)
{
//--- increase the array size
default_size+=100;
ArrayResize(cand_buff,default_size);
}
}
//--- close the file
1325
File Functions
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
return(INIT_FAILED);
}
//--- indicator buffers mapping
SetIndexBuffer(0,open_buff,INDICATOR_DATA);
SetIndexBuffer(1,high_buff,INDICATOR_DATA);
SetIndexBuffer(2,low_buff,INDICATOR_DATA);
SetIndexBuffer(3,close_buff,INDICATOR_DATA);
//--- empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
//--- the loop for the candlesticks that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
open_buff[i]=0;
close_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, the value from the file is used
if(time[i]==cand_buff[j].date)
{
1326
File Functions
open_buff[i]=cand_buff[j].open;
close_buff[i]=cand_buff[j].close;
high_buff[i]=cand_buff[j].high;
low_buff[i]=cand_buff[j].low;
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Structures and classes, FileWriteStruct
1327
File Functions
FileSeek
The function moves the position of the file pointer by a specified number of bytes relative to the
specified position.
bool FileSeek(
int
file_handle,
// File handle
long
offset,
// In bytes
ENUM_FILE_POSITION
origin
);
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
If successful the function returns true, otherwise false. To obtain information about the error call
the GetLastError() function.
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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileSeek.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt";
// file name
// directory name
input int
//+------------------------------------------------------------------+
1328
File Functions
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- specify the value of the variable for generating random numbers
_RandomSeed=GetTickCount();
//--- variables for positions of the strings' start points
ulong pos[];
int
size;
//+-------------------------------------------------------------------------------+
void GetStringPositions(const int handle,ulong &arr[])
{
//--- default array size
1329
File Functions
int def_size=127;
//--- allocate memory for the array
ArrayResize(arr,def_size);
//--- string counter
int i=0;
//--- if this is not the file's end, then there is at least one string
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // the file is empty, exit
//--- define the shift in bytes depending on encoding
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
shift=1;
else
shift=2;
//--- go through the strings in the loop
while(1)
{
//--- read the string
FileReadString(handle);
//--- check for the file end
if(!FileIsEnding(handle))
{
//--- store the next string's position
arr[i]=FileTell(handle)+shift;
i++;
//--- increase the size of the array if it is overflown
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // end of the file, exit
}
//--- define the actual size of the array
ArrayResize(arr,i);
}
1330
File Functions
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
The value of type int.
Note
To obtain information about the error call GetLastError().
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input ulong
InpThresholdSize=20;
//+------------------------------------------------------------------+
void OnStart()
{
string
file_name;
string
ulong
file_size=0;
int
size=0;
// number of files
//--- print the path to the file we are going to work with
PrintFormat("Working in %s\\Files\\ folder",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//--- receive the search handle in common folder's root of all terminals
long search_handle=FileFindFirst(filter,file_name,FILE_COMMON);
//--- check if FileFindFirst() has been executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- move files in the loop according to their size
do
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(file_name,FILE_READ|FILE_CSV|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
1331
File Functions
{
//--- receive the file size
file_size=FileSize(file_handle);
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",file_name,GetLastError());
continue;
}
//--- print the file size
PrintFormat("Size of %s file is equal to %d bytes",file_name,file_size);
//--- define the path for moving the file
string path;
if(file_size>InpThresholdSize*1024)
path=InpBigFolderName+"//"+file_name;
else
path=InpSmallFolderName+"//"+file_name;
//--- move the file
ResetLastError();
if(FileMove(file_name,FILE_COMMON,path,FILE_REWRITE|FILE_COMMON))
PrintFormat("%s file is moved",file_name);
else
PrintFormat("Error, code = %d",GetLastError());
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
1332
File Functions
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
To obtain information about the error call GetLastError().
Example:
//+------------------------------------------------------------------+
//|
Demo_FileTell.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt";
// file name
// directory name
input int
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- specify the value of the variable for generating random numbers
_RandomSeed=GetTickCount();
//--- variables for positions of the strings' start points
ulong pos[];
int
size;
1333
File Functions
{
PrintFormat("%s file is available for reading",InpFileName);
//--- receive start position for each string in the file
GetStringPositions(file_handle,pos);
//--- define the number of strings in the file
size=ArraySize(pos);
if(!size)
{
//--- stop if the file does not have strings
PrintFormat("%s file is empty!",InpFileName);
FileClose(file_handle);
return;
}
//--- make a random selection of a string number
int ind=MathRand()%size;
//--- shift position to the starting point of the string
FileSeek(file_handle,pos[ind],SEEK_SET);
//--- read and print the string with ind number
PrintFormat("String text with %d number: \"%s\"",ind,FileReadString(file_handle));
//--- close the file
FileClose(file_handle);
PrintFormat("%s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
//+-------------------------------------------------------------------------------+
//| The function defines starting points for each of the strings in the file and
//+-------------------------------------------------------------------------------+
void GetStringPositions(const int handle,ulong &arr[])
{
//--- default array size
int def_size=127;
//--- allocate memory for the array
ArrayResize(arr,def_size);
//--- string counter
int i=0;
//--- if this is not the file's end, then there is at least one string
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // the file is empty, exit
//--- define the shift in bytes depending on encoding
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
1334
File Functions
shift=1;
else
shift=2;
//--- go through the strings in the loop
while(1)
{
//--- read the string
FileReadString(handle);
//--- check for the file end
if(!FileIsEnding(handle))
{
//--- store the next string's position
arr[i]=FileTell(handle)+shift;
i++;
//--- increase the size of the array if it is overflown
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // end of the file, exit
}
//--- define the actual size of the array
ArrayResize(arr,i);
}
1335
File Functions
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
...
);
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
Number of bytes written.
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".
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWrite.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURUSD";
// currency pair
input ENUM_TIMEFRAMES
InpSymbolPeriod=PERIOD_H1;
// time frame
input int
InpFastEMAPeriod=12;
input int
InpSlowEMAPeriod=26;
input int
InpSignalPeriod=9;
// price type
1336
File Functions
input datetime
InpFileName="MACD.csv";
// file name
input string
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish; // data copying end date
bool
double
int macd_handle=iMACD(InpSymbolName,InpSymbolPeriod,InpFastEMAPeriod,InpSlowEMAPeriod,InpSignalP
if(macd_handle==INVALID_HANDLE)
{
//--- failed to receive indicator handle
PrintFormat("Error when receiving indicator handle. Error code = %d",GetLastError());
return;
}
//--- being in the loop until the indicator calculates all its values
while(BarsCalculated(macd_handle)==-1)
Sleep(10); // pause to allow the indicator to calculate all its values
//--- copy the indicator values for a certain period of time
ResetLastError();
if(CopyBuffer(macd_handle,0,InpDateStart,date_finish,macd_buff)==-1)
{
PrintFormat("Failed to copy indicator values. Error code = %d",GetLastError());
return;
}
//--- copy the appropriate time for the indicator values
ResetLastError();
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,date_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- free the memory occupied by the indicator
IndicatorRelease(macd_handle);
//--- receive the buffer size
macd_size=ArraySize(macd_buff);
//--- analyze the data and save the indicator signals to the arrays
1337
File Functions
ArrayResize(sign_buff,macd_size-1);
ArrayResize(time_buff,macd_size-1);
for(int i=1;i<macd_size;i++)
{
//--- buy signal
if(macd_buff[i-1]<0 && macd_buff[i]>=0)
{
sign_buff[sign_size]=true;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
//--- sell signal
if(macd_buff[i-1]>0 && macd_buff[i]<=0)
{
sign_buff[sign_size]=false;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
}
//--- open the file for writing the indicator values (if the file is absent, it will be created aut
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the number of signals
FileWrite(file_handle,sign_size);
//--- write the time and values of signals to the file
for(int i=0;i<sign_size;i++)
FileWrite(file_handle,time_buff[i],sign_buff[i]);
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
Comment, Print, StringFormat
1338
File Functions
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
// Array
int
start=0,
int
count=WHOLE_ARRAY
// Number of elements
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
array[]
[out] Array for recording.
start=0
[in] Initial index in the array (number of the first recorded element).
count=WHOLE_ARRAY
[in] Number of items to write (WHOLE_ARRAY means that all items starting with the number start
until the end of the array will be written).
Return Value
Number of recorded items.
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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteArray.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//+------------------------------------------------------------------+
1339
File Functions
struct prices
{
datetime
date; // date
double
bid;
// bid price
double
ask;
// ask price
};
//--- global variables
int
count=0;
int
size=20;
string path=InpDirectoryName+"//"+InpFileName;
prices arr[];
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- allocate memory for the array
ArrayResize(arr,size);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- write the remaining count strings if count<n
WriteData(count);
}
//+------------------------------------------------------------------+
//| Expert tick function
//+------------------------------------------------------------------+
void OnTick()
{
//--- save data to array
arr[count].date=TimeCurrent();
arr[count].bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
arr[count].ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//--- show current data
Print("Date = ",arr[count].date," Bid = ",arr[count].bid," Ask = ",arr[count].ask);
//--- increase the counter
count++;
//--- if the array is filled, write data to the file and zero it out
if(count==size)
{
WriteData(size);
count=0;
}
}
1340
File Functions
//+------------------------------------------------------------------+
//| Write n elements of the array to file
//+------------------------------------------------------------------+
void WriteData(const int n)
{
//--- open the file
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN);
if(handle!=INVALID_HANDLE)
{
//--- write array data to the end of the file
FileSeek(handle,0,SEEK_END);
FileWriteArray(handle,arr,0,n);
//--- close the file
FileClose(handle);
}
else
Print("Failed to open the file, error ",GetLastError());
}
See also
Variables, FileSeek
1341
File Functions
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 value
// Value to write
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteDouble.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURJPY";
// currency pair
input ENUM_TIMEFRAMES
InpSymbolPeriod=PERIOD_M15;
// time frame
input int
InpMAPeriod=10;
// smoothing period
input int
InpMAShift=0;
// indicator shift
input ENUM_MA_METHOD
InpMAMethod=MODE_SMA;
// smoothing type
// price type
InpFileName="MA.csv";
input string
// file name
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
1342
File Functions
datetime date_finish=TimeCurrent();
double
ma_buff[];
datetime time_buff[];
int
size;
int ma_handle=iMA(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpMAShift,InpMAMethod,InpAppliedPri
if(ma_handle==INVALID_HANDLE)
{
//--- failed to receive the indicator handle
PrintFormat("Error when receiving indicator handle. Error code = %d",GetLastError());
return;
}
//--- being in the loop until the indicator calculates all its values
while(BarsCalculated(ma_handle)==-1)
Sleep(20); // a pause to allow the indicator to calculate all its values
//--- open the file for writing the indicator values (if the file is absent, it will be created aut
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the size of data sample
FileWriteDouble(file_handle,(double)size);
//--- write the indicator time and value to the file
for(int i=0;i<size;i++)
{
FileWriteDouble(file_handle,(double)time_buff[i]);
FileWriteDouble(file_handle,ma_buff[i]);
1343
File Functions
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
Real types (double, float)
1344
File Functions
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,
float value
// File handle
// Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteFloat.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURUSD";
// currency pair
// time frame
input string
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
double
close_buff[];
datetime time_buff[];
int
size;
1345
File Functions
//--- reset the error value
ResetLastError();
//--- copy the close price for each bar
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-1)
{
PrintFormat("Failed to copy close price values. Error code = %d",GetLastError());
return;
}
//--- copy the time for each bar
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy the time values. Error code = %d",GetLastError());
return;
}
//--- receive the buffer size
size=ArraySize(close_buff);
//--- open the file for writing the values (if the file is absent, it will be created automatically
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- write close prices' time and values to the file
for(int i=0;i<size;i++)
{
FileWriteDouble(file_handle,(double)time_buff[i]);
FileWriteFloat(file_handle,(float)close_buff[i]);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
Real types (double, float), FileWriteDouble
1346
File Functions
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 value,
// Value to be written
int size=INT_VALUE
// Size in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteInteger.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURUSD";
// currency pair
input ENUM_TIMEFRAMES
InpSymbolPeriod=PERIOD_H1;
// time frame
input datetime
input string
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
1347
File Functions
{
datetime date_finish=TimeCurrent();
double
close_buff[];
datetime time_buff[];
int
size;
//--- open the file for writing the values (if the file is absent, it will be created automatically
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--int
int
arr_size;
uchar arr[];
1348
File Functions
up_down=1;
}
}
else
{
if(up_down!=-1)
{
//--- write the date value to the file using FileWriteInteger
StringToCharArray(TimeToString(time_buff[i]),arr);
arr_size=ArraySize(arr);
//--- first, write the number of symbols in the array
FileWriteInteger(file_handle,arr_size,INT_VALUE);
//--- write the symbols
for(int j=0;j<arr_size;j++)
FileWriteInteger(file_handle,arr[j],CHAR_VALUE);
//--- change the trend flag
up_down=-1;
}
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
IntegerToString, StringToInteger, Integer types
1349
File Functions
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,
long value
// File handle
// Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteLong.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURUSD";
// currency pair
// time frame
input string
InpDirectoryName="Data";
// directory name
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
long
volume_buff[];
datetime time_buff[];
int
size;
1350
File Functions
//--- reset the error value
ResetLastError();
//--- copy tick volumes for each bar
if(CopyTickVolume(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,volume_buff)==-1)
{
PrintFormat("Failed to copy values of the tick volume. Error code = %d",GetLastError());
return;
}
//--- copy the time for each bar
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- receive the buffer size
size=ArraySize(volume_buff);
//--- open the file for writing the indicator values (if the file is absent, it will be created aut
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the data sample size
FileWriteLong(file_handle,(long)size);
//--- write time and volume values to file
for(int i=0;i<size;i++)
{
FileWriteLong(file_handle,(long)time_buff[i]);
FileWriteLong(file_handle,volume_buff[i]);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError());
}
See also
Integer types, FileWriteInteger
1351
File Functions
FileWriteString
The function writes the value of a string-type parameter into a BIN, CSV or TXT file starting from the
current position of the file pointer. When writing to a CSV or 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 to write
int
// number of symbols
length=-1
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
text_string
[in] String.
length=-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 CSV and 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWriteString.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
1352
File Functions
input string
InpSymbolName="EURUSD";
// currency pair
input ENUM_TIMEFRAMES
InpSymbolPeriod=PERIOD_H1;
// time frame
input int
InpMAPeriod=14;
// MA period
// price type
InpFileName="RSI.csv";
// file name
input string
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish; // data copying end date
double
rsi_buff[];
rsi_size=0;
1353
File Functions
//--- open the file for writing the indicator values (if the file is absent, it will be created aut
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV|FILE_AN
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- prepare additional variables
string str="";
bool
is_formed=false;
See also
String Type, StringFormat
1354
File Functions
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
// link to an object
int
size=-1
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
struct_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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FileWiteStruct.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string
InpSymbolName="EURUSD";
// currency pair
// time frame
InpFileName="EURUSD.txt";
// file name
input string
InpDirectoryName="Data";
// directory name
//+------------------------------------------------------------------+
//| Structure for storing candlestick data
//+------------------------------------------------------------------+
struct candlesticks
1355
File Functions
{
double
open;
// open price
double
double
high;
// high price
double
low;
// low price
datetime
date;
// date
};
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
datetime
date_finish=TimeCurrent();
int
size;
datetime
time_buff[];
double
open_buff[];
double
close_buff[];
double
high_buff[];
double
low_buff[];
candlesticks cand_buff[];
//--- reset the error value
ResetLastError();
//--- receive the time of the arrival of the bars from the range
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- receive high prices of the bars from the range
if(CopyHigh(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,high_buff)==-1)
{
PrintFormat("Failed to copy values of high prices. Error code = %d",GetLastError());
return;
}
//--- receive low prices of the bars from the range
if(CopyLow(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,low_buff)==-1)
{
PrintFormat("Failed to copy values of low prices. Error code = %d",GetLastError());
return;
}
//--- receive open prices of the bars from the range
if(CopyOpen(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,open_buff)==-1)
{
PrintFormat("Failed to copy values of open prices. Error code = %d",GetLastError());
return;
}
//--- receive close prices of the bars from the range
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-1)
{
1356
File Functions
PrintFormat("Failed to copy values of close prices. Error code = %d",GetLastError());
return;
}
//--- define dimension of the arrays
size=ArraySize(time_buff);
//--- save all data in the structure array
ArrayResize(cand_buff,size);
for(int i=0;i<size;i++)
{
cand_buff[i].open=open_buff[i];
cand_buff[i].close=close_buff[i];
cand_buff[i].high=high_buff[i];
cand_buff[i].low=low_buff[i];
cand_buff[i].date=time_buff[i];
}
//--- open the file for writing the structure array to the file (if the file is absent, it will be
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN|FILE_CO
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//--- prepare the counter of the number of bytes
uint counter=0;
//--- write array values in the loop
for(int i=0;i<size;i++)
counter+=FileWriteStruct(file_handle,cand_buff[i]);
PrintFormat("%d bytes of information is written to %s file",InpFileName,counter);
See also
Structures and classes
1357
File Functions
FolderCreate
The function creates a folder in the Files directory (depending on the value of common_flag).
bool FolderCreate(
string folder_name,
int
// Scope
common_flag=0
);
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 \Terminal\Common\Files. Otherwise, the
directory is in a local folder (MQL5\Files or MQL5\Tester\Files in case of testing).
Return Value
Returns true if successful, otherwise - false.
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:
//+------------------------------------------------------------------+
//|
Demo_FolderCreate.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- Description
#property description "The script shows a sample use of FolderCreate()."
#property description "An external parameter defines the folder for creating folders."
#property description "After running the script, a structure of folders is created"
//--- Show the dialog of input parameters when starting the script
#property script_show_inputs
//--- The input parameter defines the folder, in which the script is running
input bool
int
flag=0;
// The flag value determines the place for running file operati
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
1358
File Functions
{
string working_folder;
//--- Set the flag value, if the external parameter common_folder==true
if(common_folder)
{
flag=FILE_COMMON;
//--- Find the folder, in which we are working
working_folder=TerminalInfoString(TERMINAL_COMMONDATA_PATH)+"\\MQL5\\Files";
}
else working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL5\\Files";
//--- The folder that will be created in the folder MQL5\Files
string root="Folder_A";
if(CreateFolder(working_folder,root,flag))
{
//--- Create a child folder in it Child_Folder_B1
string folder_B1="Child_Folder_B1";
string path=root+"\\"+folder_B1;
if(CreateFolder(working_folder,path,flag))
{
//--- Create 3 more child folders in this folder
string folder_C11="Child_Folder_C11";
string child_path=path+"\\"+folder_C11;// Create a folder name based on the structure
CreateFolder(working_folder,child_path,flag);
//--- The second child folder
string folder_C12="Child_Folder_C12";
child_path=path+"\\"+folder_C12;
CreateFolder(working_folder,child_path,flag);
//--- The third child folder
string folder_C13="Child_Folder_C13";
child_path=path+"\\"+folder_C13;
CreateFolder(working_folder,child_path,flag);
}
}
//--}
//+------------------------------------------------------------------+
//| Tries to create a folder and shows a message
//+------------------------------------------------------------------+
bool CreateFolder(string working_folder,string folder_path,int file_flag)
{
//--- A debug message
PrintFormat("folder_path=%s",folder_path);
//--- Trying to create a folder relative to path MQL5\Files
if(FolderCreate(folder_path,file_flag))
{
//--- Show the entire path to the created folder
PrintFormat("Folder %s has been created",working_folder+"\\"+folder_path);
//--- Reset the error code
1359
File Functions
ResetLastError();
//--- Return successful result
return true;
}
else
See also
FileOpen(), FolderClean(), FileCopy()
1360
File Functions
FolderDelete
The function removes the specified directory. If the folder is not empty, then it can't be removed.
bool FolderDelete(
string folder_name,
int
// Scope
common_flag=0
);
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 \Terminal\Common\Files. Otherwise, the
directory is in a local folder (MQL5\Files or MQL5\Tester\Files in the case of testing).
Return Value
Returns true if successful, otherwise false.
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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FolderDelete.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- Description
#property description "The script shows a sample use of FolderDelete()."
#property description "First two folders are created; one of them is empty, the second one contains
#property description "When trying to delete a non-empty folder, an error is returned and a warning
//--- Show the dialog of input parameters when starting the script
#property script_show_inputs
//--- Input parameters
input string
firstFolder="empty";
input string
string filename="delete_me.txt";
// An empty folder
//+------------------------------------------------------------------+
1361
File Functions
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- Write the file handle here
int handle;
//--- Find out in what folder we are working
string working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL5\\Files";
//--- A debug message
PrintFormat("working_folder=%s",working_folder);
//--- Trying to create an empty folder relative to path MQL5\Files
if(FolderCreate(firstFolder,0)) // 0 means that we are working in the local folder of the termin
{
//--- Enter the full path to the created folder
PrintFormat("Folder %s has been created",working_folder+"\\"+firstFolder);
//--- Reset the error code
ResetLastError();
}
else
int choice=MessageBox(StringFormat("Do you want to delete folders %s and %s?", firstFolder, seco
"Deleting folders",
MB_YESNO|MB_ICONQUESTION); //
1362
File Functions
else
PrintFormat("Failed to delete folder %s. Error code=%d", firstFolder, GetLastError());
ResetLastError();
//--- Delete the folder that contains a file
if(FolderDelete(secondFolder))
PrintFormat("Folder %s has been successfully deleted", secondFolder);
else
//--- The following message should appear since the folder contains a file
PrintFormat("Failed to delete folder %s. Error code=%d", secondFolder, GetLastError());
}
else
Print("Deletion canceled");
//--}
See also
FileOpen(), FolderClean(), FileMove()
1363
File Functions
FolderClean
The function deletes all files in a specified folder.
bool FolderClean(
string folder_name,
int
// Scope
common_flag=0
);
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 \Terminal\Common\Files. Otherwise, the
directory is in a local folder(MQL5\Files or MQL5\Tester\Files in case of testing).
Return Value
Returns true if successful, otherwise false.
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.
Example:
//+------------------------------------------------------------------+
//|
Demo_FolderClean.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
//--- Description
#property description "The script shows a sample use of FolderClean()."
#property description "First, files are created in the specified folder using the FileOpen() functi
#property description "Then, before the files are deleted, a warning is shown using MessageBox()."
//--- Show the dialog of input parameters when starting the script
#property script_show_inputs
//--- Input parameters
input string
foldername="demo_folder";
input int
files=5;
//+------------------------------------------------------------------+
1364
File Functions
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
string name="testfile";
//--- First open or create files in the terminal data folder
for(int N=0;N<files;N++)
{
//--- The name of the file in the form of 'demo_folder\testfileN.txt'
string filemane=StringFormat("%s\\%s%d.txt",foldername,name,N);
//--- Open a file with the flag for writing, in this case the 'demo_folder' will be created a
int handle=FileOpen(filemane,FILE_WRITE);
//--- Find out if the FileOpen() function was successful
if(handle==INVALID_HANDLE)
{
PrintFormat("Failed to create file %s. Error code",filemane,GetLastError());
ResetLastError();
}
else
{
PrintFormat("File %s has been successfully opened",filemane);
//--- The opened file is not needed any more, so close it
FileClose(handle);
}
}
//--- Check the number of files in the folder
int k=FilesInFolder(foldername+"\\*.*",0);
PrintFormat("Totally the folder %s contains %d files",foldername,k);
//--- Show a dialog to ask the user
int choice=MessageBox(StringFormat("You are going to delete %d files from folder %s. Do you want
"Deleting files from the folder",
MB_YESNO|MB_ICONQUESTION); //
ResetLastError();
//--- Run an action depending on the selected variant
if(choice==IDYES)
{
//--- Start to delete files
PrintFormat("Trying to delete all files from folder %s",foldername);
if(FolderClean(foldername,0))
PrintFormat("Files have been successfully deleted, %d files left in folder %s",
foldername,
FilesInFolder(foldername+"\\*.*",0));
else
1365
File Functions
//--}
//+------------------------------------------------------------------+
//| Returns the number of files in the specified folder
//+------------------------------------------------------------------+
int FilesInFolder(string path,int flag)
{
int count=0;
long handle;
string filename;
//--handle=FileFindFirst(path,filename,flag);
//--- If at least one file found, search for more files
if(handle!=INVALID_HANDLE)
{
//--- Show the name of the file
PrintFormat("File %s found",filename);
//--- Increase the counter of found files/folders
count++;
//--- Start search in all files/folders
while(FileFindNext(handle,filename))
{
PrintFormat("File %s found",filename);
count++;
}
//--- Do not forget to close the search handle upon completion
FileFindClose(handle);
}
else // Failed to get the handle
{
PrintFormat("Files search in folder %s failed",path);
}
//--- Return the result
return count;
}
See also
FileFindFirst, FileFindNext, FileFindClose
1366
Custom Indicators
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
SetIndexBuffer
Binds the specified indicator buffer with onedimensional dynamic array of the double type
IndicatorSetDouble
IndicatorSetInteger
IndicatorSetString
PlotIndexSetDouble
PlotIndexSetInteger
PlotIndexSetString
PlotIndexGetInteger
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
1367
Custom Indicators
indicator:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Label1"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
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);
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:
1368
Custom Indicators
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:
//--- sets first bar from which index will be drawn
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,37);
1369
Custom Indicators
need to accept for calculation (empty_first_values). Thus, we have mechanisms to:
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.
1370
Custom Indicators
2 // number of plots
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:
Plotting
Description
Value buffers
Color buffers
DRAW_NONE
Is
not
visually
displayed in the chart,
but the values of the
corresponding buffer
can be viewed in the
Data Window
DRAW_LINE
DRAW_SECTION
Is drawn as line
segments between the
values
of
the
corresponding buffer
(usually has a lot of
1371
Custom Indicators
empty values)
DRAW_HISTOGRAM
Is
drawn
as
a
histogram from the
zero line to the values
of the corresponding
buffer
(may
have
empty values)
DRAW_HISTOGRAM2
Is
drawn
as
a
histogram based on
two indicator buffers
(may
have
empty
values)
DRAW_ARROW
Is drawn as symbols
(may
have
empty
values)
DRAW_ZIGZAG
DRAW_FILLING
DRAW_BARS
Is drawn as bars. 4
values
of
the
corresponding buffers
are shown in the Data
Window
DRAW_CANDLES
Drawn as Japanese
candlesticks. 4 values
of the corresponding
buffers are shown in
the Data Window
DRAW_COLOR_LINE
DRAW_COLOR_SECTIO
N
1372
Custom Indicators
DRAW_COLOR_HISTO
GRAM
DRAW_COLOR_HISTO
GRAM2
DRAW_COLOR_ARRO
W
DRAW_COLOR_ZIGZAG
The
DRAW_ZIGZAG
style with the options
of individual coloring
of
sections
and
dynamic color changing
DRAW_COLOR_BARS
DRAW_COLOR_CANDL
ES
The DRAW_CANDLES
style with the options
of individual coloring
of candlesticks and
dynamic color changing
1373
Custom Indicators
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:
#property indicator_buffers 3
//
DRAW_CANDLES
clrDodgerBlue
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.
//--- Binding arrays with indicator buffers
SetIndexBuffer(0,OBuffer,INDICATOR_DATA);
SetIndexBuffer(1,HBuffer,INDICATOR_DATA);
SetIndexBuffer(2,LBuffer,INDICATOR_DATA);
SetIndexBuffer(3,CBuffer,INDICATOR_DATA);
1374
Custom Indicators
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 number of buffers and the number of plots has
increased.
//--- The indicator has 5 indicator buffers
#property indicator_buffers 5
//--- The indicator has 2 plots
#property indicator_plots
DRAW_LINE
clrDodgerRed
DRAW_CANDLES
clrDodgerBlue
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.
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
SetIndexBuffer(2,HBuffer,INDICATOR_DATA);
SetIndexBuffer(3,LBuffer,INDICATOR_DATA);
SetIndexBuffer(4,CBuffer,INDICATOR_DATA);
The number of buffers and plots can be set only by using compiler directives, it is impossible to
change these properties dynamically using functions.
1375
Custom Indicators
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 specify 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.
//--- set the candlestick color clrRed
col_buffer[buffer_index]=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,
//
1376
Custom Indicators
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
color_array[i]);
//
A new color
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.
1377
Custom Indicators
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(INIT_SUCCEEDED);
}
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 |
//|
//|
https://www.mql5.com |
1378
Custom Indicators
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Bar Index"
#property indicator_type1
DRAW_NONE
#property indicator_style1
STYLE_SOLID
#property indicator_color1
clrRed
#property indicator_width1
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(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
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);
1379
Custom Indicators
}
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;
}
1380
Custom Indicators
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.
The number of buffers required for plotting DRAW_LINE is 1.
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1381
Custom Indicators
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"Line"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
// Line color
#property indicator_style1
#property indicator_width1
// Line Width
N=5;
LineBuffer[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
//--- Initializing the generator of pseudo-random numbers
MathSrand(GetTickCount());
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
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)
{
1382
Custom Indicators
//--- Change the line properties
ChangeLineAppearance();
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- Block for calculating indicator values
for(int i=0;i<rates_total;i++)
{
LineBuffer[i]=close[i];
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the appearance of the drawn line in the indicator
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the line properties
string comm="";
//--- A block for changing the color of the line
//--- Get a random number
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];
//--- A block for changing the width of the line
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);
//--- A block for changing the style of the line
number=MathRand();
//--- The divisor is equal to the size of the styles array
size=ArraySize(styles);
//--- Get the index to select a new style as the remainder of integer division
int style_index=number%size;
1383
Custom Indicators
//--- 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);
}
1384
Custom Indicators
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-empty value to another non-empty 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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_SECTION,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the values of the indicator buffers, set an empty value in a buffer to the
elements that should not be plotted.
The number of buffers required for plotting DRAW_SECTION is 1.
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 |
//|
//|
https://www.mql5.com |
1385
Custom Indicators
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"Section"
#property indicator_type1
DRAW_SECTION
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
bars=5;
input int
N=5;
SectionBuffer[];
divider;
//+------------------------------------------------------------------+
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(INIT_PARAMETERS_INCORRECT);
}
else divider=2*bars;
//---+
return(INIT_SUCCEEDED);
}
1386
Custom Indicators
//+------------------------------------------------------------------+
//| 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;
}
1387
Custom Indicators
}
//--- 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];
//--- A block for changing the width of the line
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1388
Custom Indicators
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.
The number of buffers required for plotting DRAW_HISTOGRAM is 1.
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
1389
Custom Indicators
#property link
"https://www.mql5.com"
#property version
"1.00"
"Histogram"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
bars=30;
input int
N=5;
HistogramBuffer[];
//--- A factor to get the 2Pi angle in radians, when multiplied by the bars parameter
double
multiplier;
//+------------------------------------------------------------------+
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(INIT_PARAMETERS_INCORRECT);
}
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
1390
Custom Indicators
//+------------------------------------------------------------------+
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;
}
//--- Calculate the indicator values
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++)
{
HistogramBuffer[i]=sin(i*multiplier);
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the appearance of lines in the indicator
//+------------------------------------------------------------------+
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_index=number%size;
1391
Custom Indicators
//--- 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];
//--- A block for changing the width of the line
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1392
Custom Indicators
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 empty values nothing is drawn, all the values in the indicator buffers need to be set explicitly.
Buffers are not initialized with a zero value.
The number of buffers required for plotting DRAW_HISTOGRAM2 is 2.
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
day of week 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:
//--- Set an empty value
PlotIndexSetDouble(index_of_plot_DRAW_SECTION,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 |
//|
//|
https://www.mql5.com |
1393
Custom Indicators
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"Histogram_2"
#property indicator_type1
DRAW_HISTOGRAM2
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
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(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
1394
Custom Indicators
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;
}
//--- Calculate the indicator values
int start=0;
//--- To get the day of week by the open price of each bar
MqlDateTime dt;
//--- 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++)
{
TimeToStruct(time[i],dt);
if(dt.day_of_week==invisible_day)
{
Histogram_2Buffer1[i]=0;
Histogram_2Buffer2[i]=0;
}
else
{
Histogram_2Buffer1[i]=open[i];
Histogram_2Buffer2[i]=close[i];
}
}
//--- Return the prev_calculated value for the next call of the function
return(rates_total);
}
//+------------------------------------------------------------------+
//| Changes the appearance of lines in the indicator
//+------------------------------------------------------------------+
1395
Custom Indicators
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];
//--- A block for changing the width of the line
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1396
Custom Indicators
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.
The symbol code is set using the PLOT_ARROW property.
//--- Define the symbol code from the Wingdings font to draw in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
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.
Empty 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.
//--- Set an empty value
PlotIndexSetDouble(index_of_plot_DRAW_ARROW,PLOT_EMPTY_VALUE,0);
1397
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"Arrows"
#property indicator_type1
DRAW_ARROW
#property indicator_color1
clrGreen
#property indicator_width1
N=5;
1398
Custom Indicators
input ushort
code=159;
ArrowsBuffer[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ArrowsBuffer,INDICATOR_DATA);
//--- Define the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
//--- Set the vertical shift of arrows in pixels
PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,5);
//--- Set as an empty value 0
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the color, size, shift and code of the arrow
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;
}
//--- Block for calculating indicator values
int start=1;
1399
Custom Indicators
if(prev_calculated>0) start=prev_calculated-1;
//--- Calculation loop
for(int i=1;i<rates_total;i++)
{
//--- If the current Close price is higher than the previous one, draw an arrow
if(close[i]>close[i-1])
ArrowsBuffer[i]=close[i];
//--- Otherwise specify the zero value
else
ArrowsBuffer[i]=0;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Change the appearance of symbols in the indicator
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the indicator properties
string comm="";
//--- A block for changing the arrow color
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];
//--- A block for changing the size arrows
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1400
Custom Indicators
1401
Custom Indicators
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 empty 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 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-empty value of one buffer to a non-empty value of another indicator
buffer. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_ZIGZAG,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the values of the indicator buffers, set an empty value in a buffer to skip bars.
The number of buffers required for plotting DRAW_ZIGZAG is 2.
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).
1402
Custom Indicators
//+------------------------------------------------------------------+
//|
DRAW_ZIGZAG.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"ZigZag"
#property indicator_type1
DRAW_ZIGZAG
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
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");
1403
Custom Indicators
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
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 day of week of each bar
MqlDateTime dt;
//--- The start position of calculations
int start=0;
//--- If the indicator was calculated on the previous tick, then start the calculation with the las
if(prev_calculated!=0) start=prev_calculated-1;
//--- Calculation loop
for(int i=start;i<rates_total;i++)
{
//--- Write the bar open time in the structure
TimeToStruct(time[i],dt);
//--- If the day of the week of this bar is equal to invisible_day
if(dt.day_of_week==invisible_day)
{
//--- Write empty values to buffers for this bar
ZigZagBuffer1[i]=0;
ZigZagBuffer2[i]=0;
}
//--- If the day of the week is ok, fill in the buffers
1404
Custom Indicators
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];
//--- A block for changing the width of the line
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1405
Custom Indicators
number=MathRand();
//--- The divisor is equal to the size of the styles array
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="\r\n"+EnumToString(styles[style_index])+""+comm;
//--- Add information about the day that is omitted in calculations
comm="\r\nNot plotted day - "+EnumToString((ENUM_DAY_OF_WEEK)invisible_day)+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
1406
Custom Indicators
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. It is used for
creating indicators that draw channels. None of the buffers can contain only empty values, since in this
case nothing is plotted.
You can set two fill colors:
the first color is used for the areas where values in the first buffer are greater than the values in
Drawing on the bars that do not participate in the indicator calculation will depend on the values
in the
indicator buffers:
Bars, for which the values
of both indicator buffers are equal to 0, do not participate in drawing the
indicator. It means that the area with zero values is not filled out.
drawing the indicator. The area with empty values will be filled out so that to connect the areas with
significant values.
1407
Custom Indicators
It should be noted that if the "empty value" is equal to zero, the bars that do not participate in the
indicator calculation are also filled out.
The number of buffers required for plotting DRAW_FILLING is 2.
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
1408
Custom Indicators
#property link
"https://www.mql5.com"
#property version
"1.00"
"Intersection"
#property indicator_type1
DRAW_FILLING
#property indicator_color1
clrRed,clrBlue
#property indicator_width1
Fast=13;
input int
Slow=21;
input int
shift=1;
input int
N=5;
IntersectionBuffer1[];
double
IntersectionBuffer2[];
int fast_handle;
int slow_handle;
//--- An array to store colors
color colors[]={clrRed,clrBlue,clrGreen,clrAquamarine,clrBlanchedAlmond,clrBrown,clrCoral,clrDarkSl
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,IntersectionBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,IntersectionBuffer2,INDICATOR_DATA);
//--PlotIndexSetInteger(0,PLOT_SHIFT,shift);
//--fast_handle=iMA(_Symbol,_Period,Fast,0,MODE_SMA,PRICE_CLOSE);
slow_handle=iMA(_Symbol,_Period,Slow,0,MODE_SMA,PRICE_CLOSE);
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
1409
Custom Indicators
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;
}
//--- 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
1410
Custom Indicators
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];
//--- Show the information on the chart using a comment
Comment(comm);
}
1411
Custom Indicators
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 is 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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_BARS,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the values of the indicator buffers, set an empty 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
empty 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.
1412
Custom Indicators
//+------------------------------------------------------------------+
//|
DRAW_BARS.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"Bars"
#property indicator_type1
DRAW_BARS
#property indicator_color1
clrGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
input int
bars=500;
input bool
messages=false;
BarsBuffer1[];
double
BarsBuffer2[];
double
BarsBuffer3[];
double
BarsBuffer4[];
//+------------------------------------------------------------------+
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(INIT_PARAMETERS_INCORRECT);
}
//--- indicator buffers mapping
SetIndexBuffer(0,BarsBuffer1,INDICATOR_DATA);
1413
Custom Indicators
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
//+------------------------------------------------------------------+
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
1414
Custom Indicators
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);
//--- Copy prices to the buffers
for(int i=0;i<copied;i++)
{
1415
Custom Indicators
//--- Calculate the appropriate index for the buffers
int buffer_index=total-copied+i;
//--- Write the prices to the buffers
BarsBuffer1[buffer_index]=rates[i].open;
BarsBuffer2[buffer_index]=rates[i].high;
BarsBuffer3[buffer_index]=rates[i].low;
BarsBuffer4[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 line color
comm=comm+"\r\n"+(string)colors[color_index];
//--- A block for changing the width of bars
number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1416
Custom Indicators
//--- Write the symbol name
comm="\r\n"+symbol+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
1417
Custom Indicators
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 is 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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_CANDLES,PLOT_EMPTY_VALUE,0);
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.
//+------------------------------------------------------------------+
1418
Custom Indicators
//|
DRAW_CANDLES.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"DRAW_CANDLES1"
#property indicator_type1
DRAW_CANDLES
#property indicator_color1
clrGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
input int
bars=500;
input bool
messages=false;
Candle1Buffer1[];
double
Candle1Buffer2[];
double
Candle1Buffer3[];
double
Candle1Buffer4[];
//+------------------------------------------------------------------+
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(INIT_PARAMETERS_INCORRECT);
}
//--- indicator buffers mapping
1419
Custom Indicators
SetIndexBuffer(0,Candle1Buffer1,INDICATOR_DATA);
SetIndexBuffer(1,Candle1Buffer2,INDICATOR_DATA);
SetIndexBuffer(2,Candle1Buffer3,INDICATOR_DATA);
SetIndexBuffer(3,Candle1Buffer4,INDICATOR_DATA);
//--- An empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- The name of the symbol, for which the bars are drawn
symbol=_Symbol;
//--- Set the display of the symbol
//+------------------------------------------------------------------+
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;
//--- 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 form
ChangeLineAppearance();
//--- Select a new symbol from the Market watch window
int tries=0;
//--- Make 5 attempts to fill in the buffers of plot1 with the prices from symbol
while(!CopyFromSymbolToBuffers(symbol,rates_total,0,
Candle1Buffer1,Candle1Buffer2,Candle1Buffer3,Candle1Buffer4)
&& tries<5)
{
//--- A counter of calls of the CopyFromSymbolToBuffers() function
tries++;
}
//--- Reset the counter of ticks to zero
1420
Custom Indicators
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
1421
Custom Indicators
}
//--- 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
1422
Custom Indicators
comm="\r\n"+symbol+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
1423
Custom Indicators
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.
The number of buffers required for plotting DRAW_COLOR_LINE is 2.
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
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)
1424
Custom Indicators
{
//--- The number of colors
int size=ArraySize(cols);
//--string comm=ChartGetString(0,CHART_COMMENT)+"\r\n\r\n";
//--- For each color index define a new color randomly
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,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("LineColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],true
ChartSetString(0,CHART_COMMENT,comm);
}
//--}
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1425
Custom Indicators
#property description "every N ticks"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"ColorLine"
#property indicator_type1
DRAW_COLOR_LINE
//--- Define 5 colors for coloring each bar (they are stored in the special array)
#property indicator_color1
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
input int
Length=20;
int
ColorLineBuffer[];
ColorLineColors[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,ColorLineBuffer,INDICATOR_DATA);
SetIndexBuffer(1,ColorLineColors,INDICATOR_COLOR_INDEX);
//--- Initializing the generator of pseudo-random numbers
MathSrand(GetTickCount());
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
1426
Custom Indicators
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 of line sections
ChangeColors(colors,5);
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- Block for calculating indicator values
for(int i=0;i<rates_total;i++)
{
//--- Write the indicator value into the buffer
ColorLineBuffer[i]=close[i];
//--- Now, randomly set a color index for this bar
int color_index=i%(5*Length);
color_index=color_index/Length;
//--- For this bar, the line will have the color with the index color_index
ColorLineColors[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";
//--- For each color index define a new color randomly
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;
1427
Custom Indicators
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
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);
//--- A block for changing the style of the line
number=MathRand();
//--- The divisor is equal to the size of the styles array
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);
}
1428
Custom Indicators
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 section 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-empty value to another non-empty 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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_COLOR_SECTION,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the values of the indicator buffers, set an empty value in a buffer to the
elements that should not be plotted.
The number of buffers required for plotting DRAW_COLOR_SECTION is 2.
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.
1429
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "It draws colored sections with the length equal to the specified number of b
#property description "The color, width and style of sections are changed randomly"
#property description "after every N ticks"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"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
1430
Custom Indicators
#property indicator_width1
N=5;
input int
bars_in_section=5;
divider;
int
color_sections;
ColorSectionBuffer[];
ColorSectionColors[];
//+------------------------------------------------------------------+
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;
//
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
1431
Custom Indicators
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 to plot the sections
ChangeColors(colors,color_sections);
//--- 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++)
{
//--- 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);
}
//+------------------------------------------------------------------+
1432
Custom Indicators
//| 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";
//--- For each color index define a new color randomly
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,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("SectionColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],t
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);
//--- A block for changing the style of the line
number=MathRand();
//--- The divisor is equal to the size of the styles array
int size=ArraySize(styles);
//--- Get the index to select a new style as the remainder of integer division
int style_index=number%size;
1433
Custom Indicators
//--- 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);
}
1434
Custom Indicators
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 nondisplayable values the zero value should be specified.
The number of buffers required for plotting DRAW_COLOR_HISTOGRAM is 2.
one buffer for storing a non-zero value of the vertical segment on each bar, the second end of the
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
1435
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
bars=30;
input int
N=5;
"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
Color_HistogramBuffer[];
Color_HistogramColors[];
//--- A factor to get the 2Pi angle in radians, when multiplied by the bars parameter
double
multiplier;
int
color_sections;
1436
Custom Indicators
//+------------------------------------------------------------------+
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;
//
//+------------------------------------------------------------------+
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;
}
//--- Calculate the indicator values
int start=0;
1437
Custom Indicators
//--- 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";
//--- For each color index define a new color randomly
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,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("HistogramColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i]
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
1438
Custom Indicators
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);
//--- A block for changing the style of the line
number=MathRand();
//--- The divisor is equal to the size of the styles array
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);
}
1439
Custom Indicators
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 empty values nothing is drawn, all the values in the indicator buffers need to be set
explicitly. Buffers are not initialized with empty values.
The number of buffers required for plotting DRAW_COLOR_HISTOGRAM2 is 3:
two buffers to store the upper and lower end of the vertical segment on each bar;
one 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 day of week, 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).
1440
Custom Indicators
//+------------------------------------------------------------------+
//|
DRAW_COLOR_HISTOGRAM2.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"ColorHistogram_2"
#property indicator_type1
DRAW_COLOR_HISTOGRAM2
//--- Define 5 colors for coloring the histogram based on the days of week (they are stored in the
#property indicator_color1
clrRed,clrBlue,clrGreen,clrYellow,clrMagenta
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
int
color_sections;
ColorHistogram_2Buffer1[];
double
ColorHistogram_2Buffer2[];
ColorHistogram_2Colors[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorHistogram_2Buffer1,INDICATOR_DATA);
SetIndexBuffer(1,ColorHistogram_2Buffer2,INDICATOR_DATA);
1441
Custom Indicators
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;
//
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
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;
}
//--- Calculate the indicator values
int start=0;
//--- To get the day of week by the open price of each bar
MqlDateTime dt;
//--- 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++)
{
TimeToStruct(time[i],dt);
//--- value
ColorHistogram_2Buffer1[i]=high[i];
ColorHistogram_2Buffer2[i]=low[i];
1442
Custom Indicators
//--- Set the color index according to the day of week
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";
//--- For each color index define a new color randomly
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 division
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("HistogramColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i]
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
1443
Custom Indicators
comm=comm+" Width="+IntegerToString(width);
//--- A block for changing the style of the line
number=MathRand();
//--- The divisor is equal to the size of the styles array
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);
}
1444
Custom Indicators
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.
The symbol code is set using the PLOT_ARROW property.
//--- Define the symbol code from the Wingdings font to draw in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
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. Empty 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.
//--- Set an empty value
PlotIndexSetDouble(DRAW_COLOR_ARROW_plot_index,PLOT_EMPTY_VALUE,0);
empty values).
An example of the indicator, which draws arrows on each bar with 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.
1445
Custom Indicators
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 set 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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"ColorArrow"
#property indicator_type1
DRAW_COLOR_ARROW
1446
Custom Indicators
//--- Define 8 colors for coloring the histogram (they are stored in the special array)
#property indicator_color1
clrRed,clrBlue,clrSeaGreen,clrGold,clrDarkOrange,clrMagenta,clrYellowGr
#property indicator_style1
STYLE_SOLID
#property indicator_width1
N=5;
input ushort
code=159;
int
color_sections;
ColorArrowBuffer[];
ColorArrowColors[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorArrowBuffer,INDICATOR_DATA);
SetIndexBuffer(1,ColorArrowColors,INDICATOR_COLOR_INDEX);
//--- Define the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,code);
//--- Set the vertical shift of arrows in pixels
PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,5);
//--- Set as an empty value 0
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---- The number of colors to color the sinusoid
color_sections=8;
//
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
1447
Custom Indicators
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Calculate ticks to change the color, size, shift and code of the arrow
ticks++;
//--- If a critical number of ticks has been accumulated
if(ticks>=N)
{
//--- Change arrow properties
ChangeLineAppearance();
//--- Change the colors used to draw the histogram
ChangeColors(colors,color_sections);
//--- Reset the counter of ticks to zero
ticks=0;
}
//--- Block for calculating indicator values
int start=1;
if(prev_calculated>0) start=prev_calculated-1;
//--- Calculation loop
for(int i=1;i<rates_total;i++)
{
//--- If the current Close price is higher than the previous one, draw an arrow
if(close[i]>close[i-1])
ColorArrowBuffer[i]=close[i];
//--- Otherwise specify the null value
else
ColorArrowBuffer[i]=0;
//--- Arrow color
int index=i%color_sections;
ColorArrowColors[i]=index;
}
//--- return value of prev_calculated for next call
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";
//--- For each color index define a new color randomly
for(int plot_color_ind=0;plot_color_ind<plot_colors;plot_color_ind++)
{
1448
Custom Indicators
//--- Get a random value
int number=MathRand();
//--- Get an index in the col[] array as a remainder of the integer division
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
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);
//--- A block for changing the arrow code (PLOT_ARROW)
number=MathRand();
//--- Get the remainder of integer division to calculate a new code of the arrow (from 0 to 19)
int code_add=number%20;
//--- Set the new symbol code as the result of code+code_add
PlotIndexSetInteger(0,PLOT_ARROW,code+code_add);
//--- Write the symbol code PLOT_ARROW
comm="\r\n"+"PLOT_ARROW="+IntegerToString(code+code_add)+comm;
//--- A block for changing the vertical shift of arrows in pixels
number=MathRand();
//--- Get the shift as the remainder of the integer division
int shift=20-number%41;
//--- Set the new shift from
PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,shift);
//--- Write the shift PLOT_ARROW_SHIFT
comm="\r\n"+"PLOT_ARROW_SHIFT="+IntegerToString(shift)+comm;
1449
Custom Indicators
//--- Show the information on the chart using a comment
Comment(comm);
}
1450
Custom Indicators
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 empty 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-empty value of one buffer to a non-empty value of another indicator
buffer. To specify what value should be considered as "empty", set this value in the
PLOT_EMPTY_VALUE property:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_COLOR_ZIGZAG,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the of the indicator buffers, set an empty value in a buffer to skip bars.
The number of buffers required for plotting DRAW_COLOR_ZIGZAG is 3:
two buffers to store the 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
1451
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"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
N=5;
int
color_sections;
Color_ZigzagBuffer1[];
double
Color_ZigzagBuffer2[];
Color_ZigzagColors[];
//+------------------------------------------------------------------+
1452
Custom Indicators
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Color_ZigzagBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,Color_ZigzagBuffer2,INDICATOR_DATA);
SetIndexBuffer(2,Color_ZigzagColors,INDICATOR_COLOR_INDEX);
//----Number of color for coloring the zigzag
color_sections=8;
//
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
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 day of week of each bar
MqlDateTime dt;
//--- The start position of calculations
int start=0;
//--- If the indicator was calculated on the previous tick, then start the calculation with the las
if(prev_calculated!=0) start=prev_calculated-1;
//--- Calculation loop
for(int i=start;i<rates_total;i++)
{
1453
Custom Indicators
//--- Write the bar open time in the structure
TimeToStruct(time[i],dt);
//--- If the bar number is even
if(i%2==0)
{
//---
Write High in the 1st buffer and Low in the 2nd one
Color_ZigzagBuffer1[i]=high[i];
Color_ZigzagBuffer2[i]=low[i];
//--- The color of the segment
Color_ZigzagColors[i]=dt.day_of_year%color_sections;
}
//--- the bar number is odd
else
{
//--- Fill in the bar in a reverse order
Color_ZigzagBuffer1[i]=low[i];
Color_ZigzagBuffer2[i]=high[i];
//--- The color of the segment
Color_ZigzagColors[i]=dt.day_of_year%color_sections;
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| 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";
//--- For each color index define a new color randomly
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 division
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("ZigzagColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],tr
1454
Custom Indicators
ChartSetString(0,CHART_COMMENT,comm);
}
//--}
//+------------------------------------------------------------------+
//| Changes the appearance of the zigzag segments
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the properties of Color_ZigZag
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;
1455
Custom Indicators
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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_COLOR_BARS,PLOT_EMPTY_VALUE,0);
1456
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"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
N=5;
1457
Custom Indicators
input int
bars=500;
input bool
messages=false;
ColorBarsBuffer1[];
double
ColorBarsBuffer2[];
double
ColorBarsBuffer3[];
double
ColorBarsBuffer4[];
double
ColorBarsColors[];
bars_colors;
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorBarsBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,ColorBarsBuffer2,INDICATOR_DATA);
SetIndexBuffer(2,ColorBarsBuffer3,INDICATOR_DATA);
SetIndexBuffer(3,ColorBarsBuffer4,INDICATOR_DATA);
SetIndexBuffer(4,ColorBarsColors,INDICATOR_COLOR_INDEX);
//---- Number of colors for coloring bars
bars_colors=8;
//
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int ticks=0;
//--- Count ticks to change the style, color and width of the bar
1458
Custom Indicators
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();
//--- Change the colors used to draw the candlesticks
ChangeColors(colors,bars_colors);
int tries=0;
//--- Make 5 attempts to fill in the buffers with the prices from symbol
while(!CopyFromSymbolToBuffers(symbol,rates_total,bars_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);
}
//+------------------------------------------------------------------+
//| Fill in the indicator buffers with prices
//+------------------------------------------------------------------+
bool CopyFromSymbolToBuffers(string name,int total,int bar_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
1459
Custom Indicators
);
//--- 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);
//--- Copy prices to the 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
ColorBarsBuffer1[buffer_index]=rates[i].open;
ColorBarsBuffer2[buffer_index]=rates[i].high;
ColorBarsBuffer3[buffer_index]=rates[i].low;
ColorBarsBuffer4[buffer_index]=rates[i].close;
//--ColorBarsColors[buffer_index]=i%bar_colors;
}
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 color of the zigzag segments
//+------------------------------------------------------------------+
1460
Custom Indicators
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";
//--- For each color index define a new color randomly
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 division
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("BarColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],true)
ChartSetString(0,CHART_COMMENT,comm);
}
//--}
//+------------------------------------------------------------------+
//| 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 width of bars
int number=MathRand();
//--- Get the width of the remainder of integer division
int width=number%5;
1461
Custom Indicators
1462
Custom Indicators
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:
//--- The 0 (empty) value will mot participate in drawing
PlotIndexSetDouble(index_of_plot_DRAW_COLOR_CANDLES,PLOT_EMPTY_VALUE,0);
Always explicitly fill in the values of the indicator buffers, set an empty value in a buffer to skip bars.
The number of required buffers for plotting DRAW_COLOR_CANDLES is 5:
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
1463
Custom Indicators
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
"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
1464
Custom Indicators
//--- input parameters
input int
N=5;
input int
bars=500;
input bool
messages=false;
ColorCandlesBuffer1[];
double
ColorCandlesBuffer2[];
double
ColorCandlesBuffer3[];
double
ColorCandlesBuffer4[];
double
ColorCandlesColors[];
int
candles_colors;
//+------------------------------------------------------------------+
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(INIT_PARAMETERS_INCORRECT);
}
//--- indicator buffers mapping
SetIndexBuffer(0,ColorCandlesBuffer1,INDICATOR_DATA);
SetIndexBuffer(1,ColorCandlesBuffer2,INDICATOR_DATA);
SetIndexBuffer(2,ColorCandlesBuffer3,INDICATOR_DATA);
SetIndexBuffer(3,ColorCandlesBuffer4,INDICATOR_DATA);
SetIndexBuffer(4,ColorCandlesColors,INDICATOR_COLOR_INDEX);
//--- An empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- The name of the symbol, for which the bars are drawn
symbol=_Symbol;
//--- Set the display of the symbol
//
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
1465
Custom Indicators
//| 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[],
1466
Custom Indicators
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
1467
Custom Indicators
//--- 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;
//--- Set the candlestick color
int color_index=i%cndl_colors;
col_buffer[buffer_index]=color_index;
}
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 color of the candlestick 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";
//--- For each color index define a new color randomly
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 division
int i=number%size;
//--- Set the color for each index as the property PLOT_LINE_COLOR
PlotIndexSetInteger(0,
//
PLOT_LINE_COLOR,
//
Property identifier
plot_color_ind,
//
cols[i]);
//
A new color
comm=comm+StringFormat("CandleColorIndex[%d]=%s \r\n",plot_color_ind,ColorToString(cols[i],tr
1468
Custom Indicators
ChartSetString(0,CHART_COMMENT,comm);
}
//--}
//+------------------------------------------------------------------+
//| Changes the appearance of candlesticks
//+------------------------------------------------------------------+
void ChangeLineAppearance()
{
//--- A string for the formation of information about the candlestick properties
string comm="";
//--- Write the symbol name
comm="\r\n"+symbol+comm;
//--- Show the information on the chart using a comment
Comment(comm);
}
1469
Custom Indicators
Also there are other properties that can be set both through preprocessor directives and through
functions intended for custom indicator creation. These properties and corresponding functions are
described in the following table.
Directives for properties of
indicator subwindow
Functions of IndicatorSet...
() type
indicator_height
IndicatorSetInteger
(INDICATOR_INDICATOR_HEIG
HT, nHeight)
of
indicator_minimum
IndicatorSetDouble
(INDICATOR_MINIMUM,
dMaxValue)
indicator_maximum
IndicatorSetDouble
(INDICATOR_MAXIMUM,
dMinValue)
indicator_levelN
IndicatorSetDouble
(INDICATOR_LEVELVALUE,
1, nLevelValue)
no preprocessor directive
IndicatorSetString
(INDICATOR_LEVELTEXT, N-1,
sLevelName)
indicator_levelcolor
IndicatorSetInteger
(INDICATOR_LEVELCOLOR, N1, nLevelColor)
Color of N level
indicator_levelwidth
IndicatorSetInteger
(INDICATOR_LEVELWIDTH, N1, nLevelWidth)
indicator_levelstyle
IndicatorSetInteger
(INDICATOR_LEVELSTYLE, N-1,
nLevelStyle)
the
Functions of PlotIndexSet...
() type
PlotIndexSetString(N1,PLOT_LABEL,sLabel)
1470
Custom Indicators
PlotIndexSetInteger(N-1,
PLOT_LINE_COLOR, nColor)
indicator_styleN
PlotIndexSetInteger(N-1,
PLOT_LINE_STYLE, nType)
indicator_typeN
PlotIndexSetInteger(N-1,
PLOT_DRAW_TYPE, nType)
indicator_widthN
PlotIndexSetInteger(N-1,
PLOT_LINE_WIDTH, nWidth)
Common indicator
properties
Functions of IndicatorSet...
() type
the
Description
no preprocessor directive
IndicatorSetString
(INDICATOR_SHORTNAME,
sShortName)
no preprocessor directive
IndicatorSetInteger
(INDICATOR_DIGITS, nDigits)
no preprocessor directive
IndicatorSetInteger
(INDICATOR_LEVELS, nLevels)
indicator_applied_price
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
indicator_chart_window
indicator_separate_window
indicator_buffers
indicator_plots
1471
Custom Indicators
SetIndexBuffer
The function binds a specified indicator buffer with one-dimensional dynamic array of the double type.
bool SetIndexBuffer(
int
index,
// buffer index
double
buffer[],
// array
ENUM_INDEXBUFFER_TYPE data_type
);
Parameters
index
[in] Number of the indicator buffer. The numbering starts with 0. The number must be less than
the value declared in #propertyindicator_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 #propertyindicator_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
If successful, returns true, otherwise - false.
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 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
1472
Custom Indicators
//---- plot MA
#property indicator_label1
"MA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
AsSeries=true;
input int
period=15;
input ENUM_MA_METHOD
smootMode=MODE_EMA;
shift=0;
MABuffer[];
int
ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
if(AsSeries) ArraySetAsSeries(MABuffer,true);
Print("Indicator buffer is timeseries = ",ArrayGetAsSeries(MABuffer));
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("Indicator buffer after SetIndexBuffer() is timeseries = ",
ArrayGetAsSeries(MABuffer));
//--- change the order of accessing elements of the indicator buffer
ArraySetAsSeries(MABuffer,AsSeries);
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//--ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
1473
Custom Indicators
//--- Copy the values of the moving average in the buffer MABuffer
int copied=CopyBuffer(ma_handle,0,0,rates_total,MABuffer);
Print("MABuffer[0] = ",MABuffer[0]);// Depending on the value AsSeries
// Will receive a very old value
// Or for the current unfinished bar
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
See also
Custom Indicator Properties, Access to timeseries and indicators
1474
Custom Indicators
IndicatorSetDouble
The function sets the value of the corresponding indicator property. Indicator property must be of the
double type. There are two variants of the function.
Call with specifying the property identifier.
bool IndicatorSetDouble(
int
prop_id,
double prop_value
// identifier
// value to be set
);
prop_id,
// identifier
int
prop_modifier,
// modifier
double prop_value
// value to be set
Parameters
prop_id
[in]
Identifier of the indicator property. 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. Numbering of
levels starts from 0. It means that in order to set property for the second level you need to specify
1 (1 less than when using compiler directive).
prop_value
[in] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the #property directive, while
the function uses numbering from 0 (zero). In case the level number is set incorrectly, indicator
display can differ from the intended one.
For example, the first level value for the indicator in a separate subwindow can be set in two ways:
property indicator_level1 50 - the value of 1 is used for specifying the level number,
IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, 50) - 0 is used for specifying the first level.
Example: indicator that turns upside down the maximum and minimum values
of the indicator window
and values
of levels on which the horizontal lines are placed.
1475
Custom Indicators
#property indicator_separate_window
//--- set the maximum and minimum values
for the indicator window
#property indicator_minimum
#property indicator_maximum
100
//+------------------------------------------------------------------+
int OnInit()
{
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
IndicatorSetString(INDICATOR_LEVELTEXT,2,"Third Level (index 2)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetDouble() Demo");
//--- set color for each level
IndicatorSetInteger(INDICATOR_LEVELCOLOR,0,clrBlue);
IndicatorSetInteger(INDICATOR_LEVELCOLOR,1,clrGreen);
IndicatorSetInteger(INDICATOR_LEVELCOLOR,2,clrRed);
1476
Custom Indicators
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int tick_counter=0;
static double level1=25,level2=50,level3=75;
static double max=100,min=0, shift=100;
//--- calculate ticks
tick_counter++;
//--- turn levels upside down on every 10th tick
if(tick_counter%10==0)
{
//--- invert sign for the level values
level1=-level1;
level2=-level2;
level3=-level3;
//--- invert sign for the maximum and minimum values
max-=shift;
min-=shift;
//--- invert the shift value
shift=-shift;
//--- set new level values
IndicatorSetDouble(INDICATOR_LEVELVALUE,0,level1);
IndicatorSetDouble(INDICATOR_LEVELVALUE,1,level2);
IndicatorSetDouble(INDICATOR_LEVELVALUE,2,level3);
//--- set new values of maximum and minimum in the indicator window
Print("Set up max = ",max,",
min = ",min);
IndicatorSetDouble(INDICATOR_MAXIMUM,max);
IndicatorSetDouble(INDICATOR_MINIMUM,min);
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Indicator Styles in Examples, Connection between Indicator Properties and Functions, Drawing Styles
2000-2016, MetaQuotes Software Corp.
1477
Custom Indicators
IndicatorSetInteger
The function sets the value of the corresponding indicator property. Indicator property must be of the
int or color type. There are two variants of the function.
Call with specifying the property identifier.
bool IndicatorSetInteger(
int prop_id,
// identifier
int prop_value
// value to be set
);
// identifier
int prop_modifier,
// modifier
int prop_value
// value to be set
Parameters
prop_id
[in]
Identifier of the indicator property. 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] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the #property directive, while
the function uses numbering from 0 (zero). In case the level number is set incorrectly, indicator
display can differ from the intended one.
For example, in order to set thickness of the first horizontal line use zeroth index:
IndicatorSetInteger(INDICATOR_LEVELWIDTH, 0, 5) - index 0 is used to set thickness of the first
level.
Example: indicator that sets color, style and thickness of the indicator horizontal lines.
1478
Custom Indicators
#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
//--- display three horizontal levels in a separate indicator window
#property indicator_level1 20
#property indicator_level2 50
#property indicator_level3 80
//--- set thickness of horizontal levels
#property indicator_levelwidth 5
//--- set color of horizontal levels
#property indicator_levelcolor clrAliceBlue
//--- set style of horizontal levels
#property indicator_levelstyle STYLE_DOT
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
IndicatorSetString(INDICATOR_LEVELTEXT,2,"Third Level (index 2)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetInteger() Demo");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
1479
Custom Indicators
//| 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 tick_counter=0;
//--- calculate ticks
tick_counter++;
//--- and calculate colors of horizontal levels depending on the tick counter
ChangeLevelColor(0,tick_counter,3,6,10); // three last parameters are switching the color
ChangeLevelColor(1,tick_counter,3,6,8);
ChangeLevelColor(2,tick_counter,4,7,9);
//--- modify style of horizontal levels
ChangeLevelStyle(0,tick_counter);
ChangeLevelStyle(1,tick_counter+5);
ChangeLevelStyle(2,tick_counter+15);
//--- get width as the remainder of integer division of the ticks number by 5
int width=tick_counter%5;
//--- iterate over all horizontal levels and set thickness
for(int l=0;l<3;l++)
IndicatorSetInteger(INDICATOR_LEVELWIDTH,l,width+1);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Set color of horizontal line in the separate indicator window
//+------------------------------------------------------------------+
void ChangeLevelColor(int level,
int s_trigger,
int t_trigger)
{
static color colors[3]={clrRed,clrBlue,clrGreen};
//--- index of color from the colors[] array
int index=-1;
//--- calculate the number of color from the colors[] array to paint horizontal line
if(tick_number%f_trigger==0)
index=0;
if(tick_number%s_trigger==0)
index=1;
1480
Custom Indicators
if(tick_number%t_trigger==0)
index=2;
//+------------------------------------------------------------------+
void ChangeLevelStyle(int level,
if(tick_number%40==0)
index=4;
if(tick_number%30==0)
index=3;
// ... STYLE_DOT
if(tick_number%20==0)
index=2;
// ... STYLE_DASH
if(tick_number%10==0)
index=1;
// ... STYLE_SOLID
See also
CustomIndicatorProperties, ProgramProperties(#property), Drawing Styles
1481
Custom Indicators
IndicatorSetString
The function sets the value of the corresponding indicator property. Indicator property must be of the
string type. There are two variants of the function.
Call with specifying the property identifier.
bool IndicatorSetString(
int
prop_id,
string prop_value
// identifier
// value to be set
);
prop_id,
// identifier
int
prop_modifier,
// modifier
string prop_value
// value to be set
Parameters
prop_id
[in]
Identifier of the indicator property. 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] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the #property directive, while
the function uses numbering from 0 (zero). In case the level number is set incorrectly, indicator
display can differ from the intended one.
For example, in order to set description of the first horizontal line use zeroth index:
IndicatorSetString(INDICATOR_LEVELTEXT, 0, "First Level") - index 0 is used to set text
1482
Custom Indicators
#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
//--- display three horizontal levels in a separate indicator window
#property indicator_level1 30
#property indicator_level2 50
#property indicator_level3 70
//--- set color of horizontal levels
#property indicator_levelcolor clrRed
//--- set style of horizontal levels
#property indicator_levelstyle STYLE_SOLID
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
IndicatorSetString(INDICATOR_LEVELTEXT,2,"Third Level (index 2)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetString() Demo");
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
1483
Custom Indicators
//+------------------------------------------------------------------+
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[])
{
//--//--- return value of prev_calculated for next call
return(rates_total);
}
See also
CustomIndicatorProperties, ProgramProperties(#property)
1484
Custom Indicators
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,
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
If successful, returns true, otherwise false.
1485
Custom Indicators
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.
Call indicating identifier of the property.
bool PlotIndexSetInteger(
int plot_index,
int prop_id,
// property identifier
int prop_value
// value to be set
);
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 color index properties require a modifier.
prop_value
[in] The value of the property.
Return Value
If successful, returns true, otherwise false.
Example: an indicator that draws a three-color line. The color scheme changes every 5 ticks.
1486
Custom Indicators
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"ColorLine"
#property indicator_type1
DRAW_COLOR_LINE
#property indicator_color1
clrRed,clrGreen,clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
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
//+------------------------------------------------------------------+
1487
Custom Indicators
int getIndexOfColor(int i)
{
int j=i%300;
if(j<100) return(0);// first index
if(j<200) return(1);// second index
return(2); // third index
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--static int ticks=0,modified=0;
int limit;
//--- first calculation or number of bars was changed
if(prev_calculated==0)
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);// copying failed - throw away
//--- now set line color for every bar
for(int i=0;i<rates_total;i++)
ColorBuffer[i]=getIndexOfColor(i);
}
else
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);
ticks++;// ticks counting
if(ticks>=5)//it's time to change color scheme
{
ticks=0; // reset counter
modified++; // counter of color changes
if(modified>=3)modified=0;// reset counter
ResetLastError();
switch(modified)
{
1488
Custom Indicators
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);
}
//+------------------------------------------------------------------+
1489
Custom Indicators
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,
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
If successful, returns true, otherwise false.
1490
Custom Indicators
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.
Call indicating identifier of the property.
int PlotIndexGetInteger(
int plot_index,
int prop_id,
// property identifier
);
// 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 color index 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 programmatically.
1491
Custom Indicators
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots
"ColorCandles"
#property indicator_type1
DRAW_COLOR_CANDLES
#property indicator_style1
STYLE_SOLID
#property indicator_width1
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
1492
Custom Indicators
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);
}
//+------------------------------------------------------------------+
1493
Object Functions
Object Functions
This is the group of functions intended for working with graphic objects relating to any specified
chart.
The functions defining the properties of graphical objects, as well as ObjectCreate() and ObjectMove()
operations for creating and moving objects along the chart are actually used for sending commands to
the chart. If these functions are executed successfully, the command is included in the common queue
of the chart events. Visual changes in the properties of graphical objects are implemented when
handling the queue of the chart events.
Thus, do not expect an immediate visual update of graphical objects after calling these functions.
Generally, the graphical objects on the chart are updated automatically by the terminal following the
change events - a new quote arrival, resizing the chart window, etc. Use ChartRedraw() function to
forcefully update the graphical objects.
Function
Action
ObjectCreate
ObjectName
ObjectDelete
ObjectsDeleteAll
ObjectFind
ObjectGetTimeByValue
ObjectGetValueByTime
ObjectMove
ObjectsTotal
ObjectGetDouble
ObjectGetInteger
ObjectGetString
1494
Object Functions
object property
ObjectSetDouble
ObjectSetInteger
ObjectSetString
TextSetFont
TextOut
TextGetSize
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).
1495
Object Functions
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
ENUM_OBJECT
type,
// object type
sub_window
nwin,
// window index
datetime
time1,
double
price1,
datetime
timeN=0,
double
priceN=0,
datetime
time30=0,
double
price30=0
...
...
);
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.
sub_window
[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.
1496
Object Functions
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
An object name should not exceed 63 characters.
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 function.
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.
There is a certain number of anchor points that must be specified when creating each object type:
ID
Description
Anchor Points
OBJ_VLINE
Vertical Line
OBJ_HLINE
Horizontal Line
OBJ_TREND
Trend Line
OBJ_TRENDBYANGLE
OBJ_CYCLES
Cycle Lines
OBJ_ARROWED_LINE
Arrowed Line
OBJ_CHANNEL
Equidistant Channel
OBJ_STDDEVCHANNEL
OBJ_REGRESSION
OBJ_PITCHFORK
Andrews Pitchfork
OBJ_GANNLINE
Gann Line
OBJ_GANNFAN
Gann Fan
OBJ_GANNGRID
Gann Grid
OBJ_FIBO
Fibonacci Retracement
OBJ_FIBOTIMES
OBJ_FIBOFAN
Fibonacci Fan
1497
Object Functions
OBJ_FIBOARC
Fibonacci Arcs
OBJ_FIBOCHANNEL
Fibonacci Channel
OBJ_EXPANSION
Fibonacci Expansion
OBJ_ELLIOTWAVE5
OBJ_ELLIOTWAVE3
OBJ_RECTANGLE
Rectangle
OBJ_TRIANGLE
Triangle
OBJ_ELLIPSE
Ellipse
OBJ_ARROW_THUMB_UP
Thumbs Up
OBJ_ARROW_THUMB_DOWN
Thumbs Down
OBJ_ARROW_UP
Arrow Up
OBJ_ARROW_DOWN
Arrow Down
OBJ_ARROW_STOP
Stop Sign
OBJ_ARROW_CHECK
Check Sign
OBJ_ARROW_LEFT_PRICE
OBJ_ARROW_RIGHT_PRICE
OBJ_ARROW_BUY
Buy Sign
OBJ_ARROW_SELL
Sell Sign
OBJ_ARROW
Arrow
OBJ_TEXT
Text
OBJ_LABEL
Label
OBJ_BUTTON
Button
OBJ_CHART
Chart
OBJ_BITMAP
Bitmap
OBJ_BITMAP_LABEL
Bitmap Label
1498
Object Functions
OBJ_EDIT
Edit
OBJ_EVENT
The
"Event"
object
corresponding to an event in
the economic calendar
OBJ_RECTANGLE_LABEL
1499
Object Functions
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,
int
sub_window=-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.
sub_window=-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
Name of the object is returned in case of success.
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.
1500
Object Functions
ObjectDelete
The function removes the object with the specified name from the specified chart.
bool ObjectDelete(
long
chart_id,
string name
// chart identifier
// 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.
1501
Object Functions
ObjectsDeleteAll
Removes all objects from the specified chart, specified chart subwindow, of the specified type.
int ObjectsDeleteAll(
long chart_id,
// chart identifier
int
sub_window=-1,
// window index
int
type=-1
// object type
);
Removes all objects of the specified type using prefix in object names.
int ObjectsDeleteAll(
long
chart_id,
const string
int
int
prefix,
sub_window=-1,
object_type=-1
// chart ID
// prefix in object name
// window index
// object type
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
prefix
[in] Prefix in object names. All objects whose names start with this set of characters will be
removed from chart. You can specify prefix as 'name' or 'name*' both variants will work the same.
If an empty string is specified as the prefix, objects with all possible names will be removed.
sub_window=-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().
1502
Object Functions
ObjectFind
The function searches for an object with the specified name in the chart with the specified ID.
int ObjectFind(
long
chart_id,
string name
// chart identifier
// 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.
1503
Object Functions
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 number
line_id
);
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
Linear regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
Arrowed line (OBJ_ARROWED_LINE)
See also
Object Types
1504
Object Functions
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 number
line_id
);
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
Linear regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
Arrowed line (OBJ_ARROWED_LINE)
See also
Object Types
1505
Object Functions
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,
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
[in] Time coordinate of the selected anchor point.
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().
1506
Object Functions
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
sub_window=-1,
// window index
int
type=-1
// object type
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
sub_window=-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
The number of objects.
1507
Object Functions
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.
Setting property value, without modifier
bool ObjectSetDouble(
long
chart_id,
// chart identifier
string name,
// object name
int
// property
prop_id,
double prop_value
// value
);
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
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
can
be
one
of
the
values
of
the
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().
Example of creating a Fibonacci object and adding a new level in it
//| Script program start function
//+------------------------------------------------------------------+
1508
Object Functions
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);
//--- Coordinates of the first anchor point of the Fibo object
price1=high[70];
time1=time[70];
//--- Coordinates of the second anchor point of the Fibo object
price2=low[50];
time2=time[50];
//--- Time to create the Fibo object
bool created=ObjectCreate(0,"Fibo",OBJ_FIBO,0,time1,price1,time2,price2);
if(created) // If the object is created successfully
{
//--- set the color of Fibo levels
ObjectSetInteger(0,"Fibo",OBJPROP_LEVELCOLOR,Blue);
//--- by the way, how much Fibo levels do we have?
int levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS);
Print("Fibo levels before = ",levels);
//---output to the Journal => number of level:value level_desription
for(int i=0;i<levels;i++)
1509
Object Functions
{
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
1510
Object Functions
ObjectSetInteger
The function sets the value of the corresponding object property. The object property must be of the
datetime,int,color,boolorchar type. There are 2 variants of the function.
Setting property value, without modifier
bool ObjectSetInteger(
long
chart_id,
// chart identifier
string name,
// object name
int
prop_id,
// property
long
prop_value
// value
);
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
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
can
be
one
of
the
values
of
the
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().
An example of how to create a table of Web colors
//+------------------------------------------------------------------+
//|
1511
Object Functions
//|
//|
http://www.metaquotes.net |
//+------------------------------------------------------------------+
#define X_SIZE 140
#define Y_SIZE 33
//+------------------------------------------------------------------+
//| Array of web colors
//+------------------------------------------------------------------+
color ExtClr[140]=
{
clrAliceBlue,clrAntiqueWhite,clrAqua,clrAquamarine,clrAzure,clrBeige,clrBisque,clrBlack,clrBlanc
clrBlue,clrBlueViolet,clrBrown,clrBurlyWood,clrCadetBlue,clrChartreuse,clrChocolate,clrCoral,clr
clrCornsilk,clrCrimson,clrCyan,clrDarkBlue,clrDarkCyan,clrDarkGoldenrod,clrDarkGray,clrDarkGreen
clrDarkMagenta,clrDarkOliveGreen,clrDarkOrange,clrDarkOrchid,clrDarkRed,clrDarkSalmon,clrDarkSea
clrDarkSlateBlue,clrDarkSlateGray,clrDarkTurquoise,clrDarkViolet,clrDeepPink,clrDeepSkyBlue,clrD
clrDodgerBlue,clrFireBrick,clrFloralWhite,clrForestGreen,clrFuchsia,clrGainsboro,clrGhostWhite,c
clrGoldenrod,clrGray,clrGreen,clrGreenYellow,clrHoneydew,clrHotPink,clrIndianRed,clrIndigo,clrIv
clrLavender,clrLavenderBlush,clrLawnGreen,clrLemonChiffon,clrLightBlue,clrLightCoral,clrLightCya
clrLightGoldenrod,clrLightGreen,clrLightGray,clrLightPink,clrLightSalmon,clrLightSeaGreen,clrLig
clrLightSlateGray,clrLightSteelBlue,clrLightYellow,clrLime,clrLimeGreen,clrLinen,clrMagenta,clrM
clrMediumAquamarine,clrMediumBlue,clrMediumOrchid,clrMediumPurple,clrMediumSeaGreen,clrMediumSla
clrMediumSpringGreen,clrMediumTurquoise,clrMediumVioletRed,clrMidnightBlue,clrMintCream,clrMisty
clrNavajoWhite,clrNavy,clrOldLace,clrOlive,clrOliveDrab,clrOrange,clrOrangeRed,clrOrchid,clrPale
clrPaleGreen,clrPaleTurquoise,clrPaleVioletRed,clrPapayaWhip,clrPeachPuff,clrPeru,clrPink,clrPlu
clrPurple,clrRed,clrRosyBrown,clrRoyalBlue,clrSaddleBrown,clrSalmon,clrSandyBrown,clrSeaGreen,cl
clrSienna,clrSilver,clrSkyBlue,clrSlateBlue,clrSlateGray,clrSnow,clrSpringGreen,clrSteelBlue,clr
clrThistle,clrTomato,clrTurquoise,clrViolet,clrWheat,clrWhite,clrWhiteSmoke,clrYellow,clrYellowG
};
//+------------------------------------------------------------------+
//| Creating and initializing an edit object
//+------------------------------------------------------------------+
void CreateColorBox(int x,int y,color c)
{
//--- generate a name for a new edit object
string name="ColorBox_"+(string)x+"_"+(string)y;
//--- create a new edit object
if(!ObjectCreate(0,name,OBJ_EDIT,0,0,0))
{
Print("Cannot create: '",name,"'");
return;
}
//--- set coordinates, width and height
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x*X_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y*Y_SIZE);
ObjectSetInteger(0,name,OBJPROP_XSIZE,X_SIZE);
ObjectSetInteger(0,name,OBJPROP_YSIZE,Y_SIZE);
//--- set text color
if(clrBlack==c) ObjectSetInteger(0,name,OBJPROP_COLOR,clrWhite);
else
ObjectSetInteger(0,name,OBJPROP_COLOR,clrBlack);
1512
Object Functions
//--- set background color
ObjectSetInteger(0,name,OBJPROP_BGCOLOR,c);
//--- set text
ObjectSetString(0,name,OBJPROP_TEXT,(string)c);
}
//+------------------------------------------------------------------+
//| Script program start function
//+------------------------------------------------------------------+
void OnStart()
{
//--- create 7x20 table of colored edit objects
for(uint i=0;i<140;i++)
CreateColorBox(i%7,i/7,ExtClr[i]);
}
See also
Object Types, Object Properties
1513
Object Functions
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.
Setting property value, without modifier
bool ObjectSetString(
long
chart_id,
// chart identifier
string name,
// object name
int
// property
prop_id,
string prop_value
// value
);
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
ENUM_OBJECT_PROPERTY_STRING enumeration.
can
be
one
of
the
values
of
the
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. These events can be handled in
an Expert Advisor or indicator by the OnChartEvent() function:
1514
Object Functions
an event of deletion of an object with the old name;
an event of creation of an object with a new name.
1515
Object Functions
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.
1. Immediately returns the property value.
double ObjectGetDouble(
long
chart_id,
// chart identifier
string name,
// object name
int
prop_id,
// property identifier
int
prop_modifier=0
);
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 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
);
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
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
can
be
one
of
the
values
of
the
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
Value of the double type for the first calling variant.
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().
1516
Object Functions
ObjectGetInteger
The function returns the value of the corresponding object property. The object property must be of
the datetime,int,color,boolorchar type. There are 2 variants of the function.
1. Immediately returns the property value.
long ObjectGetInteger(
long
chart_id,
// chart identifier
string name,
// object name
int
prop_id,
// property identifier
int
prop_modifier=0
);
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 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
);
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
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
can
be
one
of
the
values
of
the
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
The long value for the first calling variant.
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().
1517
Object Functions
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.
1. Immediately returns the property value.
string ObjectGetString(
long
chart_id,
// chart identifier
string name,
// object name
int
prop_id,
// property identifier
int
prop_modifier=0
);
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 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
);
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
ENUM_OBJECT_PROPERTY_STRING enumeration.
can
be
one
of
the
values
of
the
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
String value for the first version of the call.
For the second version of the call returns true, if this property is maintained and the value has been
placed into the string_var variable, otherwise returns false. To read more about the error call
GetLastError().
1518
Object Functions
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.
1519
Object Functions
TextSetFont
The function sets the font for displaying the text using drawing methods and returns the result of that
operation. Arial font with the size -120 (12 pt) is used by default.
bool TextSetFont(
const string
int
name,
size,
// font size
uint
flags,
// combination of flags
int
orientation=0
);
Parameters
name
[in] Font name in the system or the name of the resource containing the font or the path to font
file on the disk.
size
[in] The font size that can be set using positive and negative values. In case of positive values,
the size of a displayed text does not depend on the operating system's font size settings. In case
of negative values, the value is set in tenths of a point and the text size depends on the operating
system settings ("standard scale" or "large scale"). See the Note below for more information about
the differences between the modes.
flags
[in] Combination of flags describing font style.
orientation
[in] Text's horizontal inclination to X axis, the unit of measurement is 0.1 degrees. It means that
orientation=450 stands for inclination equal to 45 degrees.
Return Value
Returns true if the current font is successfully installed, otherwise false. Possible code errors:
ERR_INVALID_PARAMETER(4003) - name presents NULL or "" (empty string),
ERR_INTERNAL_ERROR(4001) - operating system error (for example, an attempt to create a non-
existent font).
Note
If "::" is used in font name, the font is downloaded from EX5 resource. If name font name is
specified with an extension, the font is downloaded from the file, if the path starts from "\" or "/",
the file is searched relative to MQL5 directory. Otherwise, it is searched relative to the path of EX5
file which called TextSetFont() function.
The font size is set using positive or negative values. This fact defines the dependence of the text
size from the operating system settings (size scale).
If the size is specified using a positive number, this size is transformed into physical measurement
units of a device (pixels) when changing a logical font into a physical one, and this size corresponds
to the height of the symbol glyphs picked from the available fonts. This case is not recommended
when the texts displayed by TextOut() function and the ones displayed by OBJ_LABEL ("Label")
graphical object are to be used together on the chart.
1520
Object Functions
If the size is specified using a negative number, this number is supposed to be set in tenths of a
logical point and is divided by 10 (for example, -350 is equal to 35 logical points). An obtained
value is then transformed into physical measurement units of a device (pixels) and corresponds to
the absolute value of the height of a symbol picked from the available fonts. Multiply the font size
specified in the object properties by -10 to make the size of a text on the screen similar to the one
in OBJ_LABEL object.
The flags can be used as the combination of style flags with one of the flags specifying the font
width. Flag names are shown below.
Flags for specifying font style
Flag
Description
FONT_ITALIC
Italic
FONT_UNDERLINE
Underline
FONT_STRIKEOUT
Strikeout
1521
Object Functions
TextOut
The function displays a text in a custom array (buffer) and returns the result of that operation. The
array is designed to create the graphical resource.
bool TextOut(
const string
text,
// displayed text
int
x,
// X coordinate
y,
// Y coordinate
int
uint
anchor,
// anchor type
uint
&data[],
// output buffer
uint
width,
uint
height,
uint
color,
// text color
color_format
ENUM_COLOR_FORMAT
);
Parameters
text
[in] Displayed text that will be written to the buffer. Only one-lined text is displayed.
x
[in] X coordinate of the anchor point of the displayed text.
y
[in] Y coordinate of the anchor point of the displayed text.
anchor
[in] The value out of the 9 pre-defined methods of the displayed text's anchor point location. The
value is set by a combination of two flags flags of horizontal and vertical text align. Flag names
are listed in the Note below.
data[]
[in] Buffer, in which text is displayed. The buffer is used to create the graphical resource.
width
[in] Buffer width in pixels.
height
[in] Buffer height in pixels.
color
[in] Text color.
color_format
[in] Color format is set by ENUM_COLOR_FORMAT enumeration value.
Return Value
Returns true if successful, otherwise false.
Note
1522
Object Functions
Anchor point specified by anchor is a combination of two flags of horizontal and vertical text align.
Horizontal text align flags:
TA_LEFT anchor point on the left side of the bounding box
TA_CENTER horizontal anchor point is located at the center of the bounding box
TA_RIGHT anchor point on the right side of the bounding box
Possible combinations of flags and specified anchor points are shown in the image.
Example:
//--- width and height of the canvas (used for drawing)
#define IMG_WIDTH
200
//+------------------------------------------------------------------+
void OnStart()
{
//--- create OBJ_BITMAP_LABEL object for drawing
ObjectCreate(0,"CLOCK",OBJ_BITMAP_LABEL,0,0,0);
//--- specify the name of the graphical resource for writing in CLOCK object
ObjectSetString(0,"CLOCK",OBJPROP_BMPFILE,"::IMG");
//--- auxiliary variables
double a;
// arrow corner
uint
nm=2700;
// minute corner
uint
nh=2700*12;
// hour counter
uint
w,h;
1523
Object Functions
int
x,y;
//--- rotate clock hands in an infinite loop, till the script is stopped
while(!IsStopped())
{
//--- clear the clock drawing buffer array
ArrayFill(ExtImg,0,IMG_WIDTH*IMG_HEIGHT,0);
//--- set the font for drawing digits for the clock-face
TextSetFont("Arial",-200,FW_EXTRABOLD,0);
//--- draw the clock-face
for(int i=1;i<=12;i++)
{
//--- receive the size of the current hour on the clock-face
TextGetSize(string(i),w,h);
//--- calculate the coordinates of the current hour on the clock-face
a=-((i*300)%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*80+0.5+w/2);
y=IMG_HEIGHT/2-int(cos(a)*80+0.5+h/2);
//--- output the hour on the clock-face to ExtImg[] buffer
TextOut(string(i),x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,clr_format);
}
//--- now, specify the font for drawing the minute hand
TextSetFont("Arial",-200,FW_EXTRABOLD,-int(nm%3600));
//--- receive the size of the minute hand
TextGetSize("----->",w,h);
//--- calculate the coordinates of the minute hand on the clock-face
a=-(nm%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*h/2+0.5);
y=IMG_HEIGHT/2-int(cos(a)*h/2+0.5);
//--- output of the minute hand to the clock-face in ExtImg[]buffer
TextOut("----->",x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,clr_format);
//--- now, set the font for drawing the minute hand
TextSetFont("Arial",-200,FW_EXTRABOLD,-int(nh/12%3600));
TextGetSize("==>",w,h);
//--- calculate the coordinates of the hour hand on the clock-face
a=-(nh/12%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*h/2+0.5);
y=IMG_HEIGHT/2-int(cos(a)*h/2+0.5);
//--- output of the hour hand on the clock-face to ExtImg[] buffer
TextOut("==>",x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,clr_format);
//--- update the graphical resource
ResourceCreate("::IMG",ExtImg,IMG_WIDTH,IMG_HEIGHT,0,0,IMG_WIDTH,clr_format);
//--- forced chart update
ChartRedraw();
//--- increase hour and minute counters
nm+=60;
nh+=60;
1524
Object Functions
//--- keeping a short pause between the frames
Sleep(10);
}
//--- delete CLOCK object when completing the script's operation
ObjectDelete(0,"CLOCK");
//--}
See also
Resources, ResourceCreate(), ResourceSave(), TextGetSize(), TextSetFont()
1525
Object Functions
TextGetSize
The function returns the line width and height at the current font settings.
bool TextGetSize(
const string
text,
// text string
uint&
width,
uint&
height
);
Parameters
text
[in] String, for which length and width should be obtained.
width
[out] Input parameter for receiving width.
height
[out] Input parameter for receiving height.
Return Value
Returns true if successful, otherwise false. Possible code errors:
ERR_INTERNAL_ERROR(4001) - operating system error.
See also
Resources, ResourceCreate(), ResourceSave(), TextSetFont(), TextOut()
1526
Technical Indicators
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.
Function
iAC
Accelerator Oscillator
iAD
Accumulation/Distribution
iADX
iADXWilder
iAlligator
Alligator
iAMA
iAO
Awesome Oscillator
1527
Technical Indicators
iATR
iBearsPower
Bears Power
iBands
Bollinger Bands
iBullsPower
Bulls Power
iCCI
iChaikin
Chaikin Oscillator
iCustom
Custom indicator
iDEMA
iDeMarker
DeMarker
iEnvelopes
Envelopes
iForce
Force Index
iFractals
Fractals
iFrAMA
iGator
Gator Oscillator
iIchimoku
iBWMFI
iMomentum
Momentum
iMFI
iMA
Moving Average
iOsMA
iMACD
iOBV
On Balance Volume
iSAR
iRSI
iRVI
iStdDev
Standard Deviation
iStochastic
Stochastic Oscillator
iTEMA
iTriX
iWPR
iVIDyA
iVolumes
Volumes
1528
Technical Indicators
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,
ENUM_TIMEFRAMES period
// symbol name
// 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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iAC.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"iAC"
#property indicator_type1
DRAW_COLOR_HISTOGRAM
#property indicator_color1
clrGreen, clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
1529
Technical Indicators
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iAC,
// use iAC
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iAC;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,iACBuffer,INDICATOR_DATA);
SetIndexBuffer(1,iACColors,INDICATOR_COLOR_INDEX);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iAC)
handle=iAC(name,period);
else
handle=IndicatorCreate(name,period,IND_AC);
//--- if the handle is not created
if(handle==INVALID_HANDLE)
1530
Technical Indicators
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iAC indicator for the symbol %s/%s, error code %d
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Accelerator Oscillator indicator is calculated for
short_name=StringFormat("iAC(%s/%s)",name,EnumToString(period));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iAC indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iACBuffer array is greater than the number of values in the iAC indicator for sy
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
1531
Technical Indicators
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iACBuffer and iACColors arrays with values from the Accelerator Oscillator indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffer(iACBuffer,iACColors,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Accelerator Oscillator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iAC indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffer(double &values[],
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iACBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAC indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- now copy the indexes of colors
if(CopyBuffer(ind_handle,1,0,amount,color_indexes)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy color values from the iAC indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
1532
Technical Indicators
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1533
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iAD.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iAD"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
1534
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iAD,
// use iAD
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iAD;
input ENUM_APPLIED_VOLUME
volumes;
// volume used
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iADBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iADBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iAD)
handle=iAD(name,period,volumes);
else
{
//--- fill the structure with parameters of the indicator
1535
Technical Indicators
MqlParam pars[1];
pars[0].type=TYPE_INT;
pars[0].integer_value=volumes;
handle=IndicatorCreate(name,period,IND_AD,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iAD indicator for the symbol %s/%s, error code %d
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Accumulation/Distribution indicator is calculated for
short_name=StringFormat("iAD(%s/%s)",name,EnumToString(period));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iAD indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
1536
Technical Indicators
//--- if the iADBuffer array is greater than the number of values in the iAD indicator for sy
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iADBuffer array with values of the Accumulation/Distribution indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArrayFromBuffer(iADBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Accumulation/Distribution indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iAD indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iADBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAD indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
1537
Technical Indicators
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1538
Technical Indicators
iADX
The function returns the handle of the Average Directional Movement Index indicator.
int iADX(
string
symbol,
// symbol name
ENUM_TIMEFRAMES period,
// period
int
// averaging period
adx_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.
Return 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
The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iADX.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots
1539
Technical Indicators
//--- plot ADX
#property indicator_label1
"ADX"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"DI_plus"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrYellowGreen
#property indicator_style2
STYLE_SOLID
#property indicator_width2
"DI_minus"
#property indicator_type3
DRAW_LINE
#property indicator_color3
clrWheat
#property indicator_style3
STYLE_SOLID
#property indicator_width3
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iADX,
// use iADX
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iADX;
input int
adx_period=14;
// period of calculation
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
ADXBuffer[];
double
DI_plusBuffer[];
double
DI_minusBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
1540
Technical Indicators
SetIndexBuffer(0,ADXBuffer,INDICATOR_DATA);
SetIndexBuffer(1,DI_plusBuffer,INDICATOR_DATA);
SetIndexBuffer(2,DI_minusBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iADX)
handle=iADX(name,period,adx_period);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
pars[0].type=TYPE_INT;
pars[0].integer_value=adx_period;
handle=IndicatorCreate(name,period,IND_ADX,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iADX indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Average Directional Movement Index indicator is calculated for
short_name=StringFormat("iADX(%s/%s period=%d)",name,EnumToString(period),adx_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
1541
Technical Indicators
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iADX indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iADXBuffer array is greater than the number of values in the iADX indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the Average Directional Movement Index indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(ADXBuffer,DI_plusBuffer,DI_minusBuffer,handle,values_to_copy)) return(
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Average Directional Movement Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iADX indicator
//+------------------------------------------------------------------+
1542
Technical Indicators
bool FillArraysFromBuffers(double &adx_values[],
double &DIplus_values[],
double &DIminus_values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iADXBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,adx_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADX indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the DI_plusBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,0,amount,DIplus_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADX indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the DI_minusBuffer array with values from the indicator buffer that has index
if(CopyBuffer(ind_handle,2,0,amount,DIminus_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADX indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1543
Technical Indicators
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
// averaging period
adx_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.
Return 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
The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.
Example:
//+------------------------------------------------------------------+
//|
iADXWilder.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots
1544
Technical Indicators
//--- plot ADX
#property indicator_label1
"ADX"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"DI_plus"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrYellowGreen
#property indicator_style2
STYLE_SOLID
#property indicator_width2
"DI_minus"
#property indicator_type3
DRAW_LINE
#property indicator_color3
clrWheat
#property indicator_style3
STYLE_SOLID
#property indicator_width3
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iADXWilder,
// use iADXWilder
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iADXWilder;
input int
adx_period=14;
// period of calculation
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
ADXBuffer[];
double
DI_plusBuffer[];
double
DI_minusBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
1545
Technical Indicators
SetIndexBuffer(0,ADXBuffer,INDICATOR_DATA);
SetIndexBuffer(1,DI_plusBuffer,INDICATOR_DATA);
SetIndexBuffer(2,DI_minusBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iADXWilder)
handle=iADXWilder(name,period,adx_period);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
pars[0].type=TYPE_INT;
pars[0].integer_value=adx_period;
handle=IndicatorCreate(name,period,IND_ADXW,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iADXWilder indicator for the symbol %s/%s, error
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Average Directional Movement Index by Welles Wilder indicator i
short_name=StringFormat("iADXWilder(%s/%s period=%d)",name,EnumToString(period),adx_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
1546
Technical Indicators
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iADXWilder indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iADXBuffer array is greater than the number of values in the iADXWilder indicato
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the Average Directional Movement Index by Welles Wilder indicat
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(ADXBuffer,DI_plusBuffer,DI_minusBuffer,handle,values_to_copy)) return(
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Average Directional Movement Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iADXWilder indicator
//+------------------------------------------------------------------+
1547
Technical Indicators
bool FillArraysFromBuffers(double &adx_values[],
double &DIplus_values[],
double &DIminus_values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iADXBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,adx_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADXWilder indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the DI_plusBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,0,amount,DIplus_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADXWilder indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the DI_plusBuffer array with values from the indicator buffer that has index 2
if(CopyBuffer(ind_handle,2,0,amount,DIminus_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iADXWilder indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1548
Technical Indicators
iAlligator
The function returns the handle of the Alligator indicator.
int iAlligator(
string
symbol,
// symbol name
ENUM_TIMEFRAMES
period,
// period
int
jaw_period,
int
jaw_shift,
int
teeth_period,
int
teeth_shift,
int
lips_period,
int
lips_shift,
ENUM_MA_METHOD
ma_method,
// type of smoothing
ENUM_APPLIED_PRICE applied_price
);
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.
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.
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.
ma_method
[in] The method 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.
1549
Technical Indicators
Return 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
The buffer numbers are the following: 0 - GATORJAW_LINE, 1 - GATORTEETH_LINE, 2 GATORLIPS_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iAlligator.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Alligator."
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots
"Jaws"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Teeth"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
"Lips"
#property indicator_type3
DRAW_LINE
#property indicator_color3
clrLime
#property indicator_style3
STYLE_SOLID
#property indicator_width3
//+------------------------------------------------------------------+
1550
Technical Indicators
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iAlligator,
// use iAlligator
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iAlligator;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
input int
jaw_period=13;
input int
jaw_shift=8;
input int
teeth_period=8;
input int
teeth_shift=5;
input int
lips_period=5;
input int
lips_shift=3;
input ENUM_MA_METHOD
MA_method=MODE_SMMA;
input ENUM_APPLIED_PRICE
JawsBuffer[];
double
TeethBuffer[];
double
LipsBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,JawsBuffer,INDICATOR_DATA);
SetIndexBuffer(1,TeethBuffer,INDICATOR_DATA);
SetIndexBuffer(2,LipsBuffer,INDICATOR_DATA);
//--- set shift of each line
PlotIndexSetInteger(0,PLOT_SHIFT,jaw_shift);
PlotIndexSetInteger(1,PLOT_SHIFT,teeth_shift);
PlotIndexSetInteger(2,PLOT_SHIFT,lips_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
1551
Technical Indicators
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iAlligator)
handle=iAlligator(name,period,jaw_period,jaw_shift,teeth_period,
teeth_shift,lips_period,lips_shift,MA_method,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[8];
1552
Technical Indicators
jaw_period,jaw_shift,teeth_period,teeth_shift,lips_period,lips_shift);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iAlligator indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the JawsBuffer array is greater than the number of values in the iAlligator indicato
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the Alligator indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(JawsBuffer,jaw_shift,TeethBuffer,teeth_shift,LipsBuffer,lips_shift,han
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
1553
Technical Indicators
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Alligator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iAlligator indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &jaws_buffer[],
int j_shift,
double &lips_buffer[],
int l_shift,
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the JawsBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-j_shift,amount,jaws_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAlligator indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the TeethBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,-t_shift,amount,teeth_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAlligator indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the LipsBuffer array with values from the indicator buffer that has index 2
if(CopyBuffer(ind_handle,2,-l_shift,amount,lips_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAlligator indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
1554
Technical Indicators
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1555
Technical Indicators
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,
int
fast_ma_period,
// fast MA period
int
slow_ma_period,
// slow MA period
int
ama_shift,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iAMA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
1556
Technical Indicators
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard AMA."
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iAMA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iAMA,
// use iAMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iAMA;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
input int
ama_period=15;
// period of calculation
input int
fast_ma_period=2;
// period of fast MA
input int
slow_ma_period=30;
// period of slow MA
input int
ama_shift=0;
// horizontal shift
input ENUM_APPLIED_PRICE
applied_price;
// type of price
iAMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
1557
Technical Indicators
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,iAMABuffer,INDICATOR_DATA);
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ama_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iAMA)
handle=iAMA(name,period,ama_period,fast_ma_period,slow_ma_period,ama_shift,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[5];
pars[0].type=TYPE_INT;
pars[0].integer_value=ama_period;
pars[1].type=TYPE_INT;
pars[1].integer_value=fast_ma_period;
pars[2].type=TYPE_INT;
pars[2].integer_value=slow_ma_period;
pars[3].type=TYPE_INT;
pars[3].integer_value=ama_shift;
//--- type of price
pars[4].type=TYPE_INT;
pars[4].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_AMA,5,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iAMA indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Adaptive Moving Average indicator is calculated for
1558
Technical Indicators
short_name=StringFormat("iAMA(%s/%s,%d,%d,%d,d)",name,EnumToString(period),ama_period,fast_ma_pe
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iAMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iAMABuffer array is greater than the number of values in the iAMA indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the Adaptive Moving Average indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArrayFromBuffer(iAMABuffer,ama_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
1559
Technical Indicators
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Adaptive Moving Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffer from the iAMA indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &ama_buffer[],
int a_shift,
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iAMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-a_shift,amount,ama_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1560
Technical Indicators
iAO
The function returns the handle of the Awesome Oscillator indicator. It has only one buffer.
int iAO(
string
symbol,
ENUM_TIMEFRAMES period
// symbol name
// 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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iAO.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"iAO"
#property indicator_type1
DRAW_COLOR_HISTOGRAM
#property indicator_color1
clrGreen,clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
1561
Technical Indicators
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iAO,
// use iAO
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iAO;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iAOBuffer[];
double
iAOColors[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,iAOBuffer,INDICATOR_DATA);
SetIndexBuffer(1,iAOColors,INDICATOR_COLOR_INDEX);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iAO)
handle=iAO(name,period);
else
handle=IndicatorCreate(name,period,IND_AO);
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
1562
Technical Indicators
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iAO indicator for the symbol %s/%s, error code %d
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Awesome Oscillator indicator is calculated for
short_name=StringFormat("iAO(%s/%s)",name,EnumToString(period));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iAO indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iAOBuffer array is greater than the number of values in the iAO indicator for sy
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
1563
Technical Indicators
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iAOBuffer and iAOColors arrays with values from the Awesome Oscillator indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffer(iAOBuffer,iAOColors,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Awesome Oscillator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iAO indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffer(double &values[],
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iAOBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iAO indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- now copy the indexes of colors
if(CopyBuffer(ind_handle,1,0,amount,color_indexes)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy color values from the iAO indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
1564
Technical Indicators
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1565
Technical Indicators
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
// averaging period
ma_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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iATR.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iATR"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
1566
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iATR,// use iATR
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input int
atr_period=14;
// period of calculation
input Creation
type=Call_iATR;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iATRBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iATRBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iATR)
handle=iATR(name,period,atr_period);
else
{
//--- fill the structure with parameters of the indicator
1567
Technical Indicators
MqlParam pars[1];
pars[0].type=TYPE_INT;
pars[0].integer_value=atr_period;
handle=IndicatorCreate(name,period,IND_ATR,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iATR indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Average True Range indicator is calculated for
short_name=StringFormat("iATR(%s/%s, period=%d)",name,EnumToString(period),atr_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iATR indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iA
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
1568
Technical Indicators
//--- if the iATRBuffer array is greater than the number of values in the iATR indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iATRBuffer array with values of the Average True Range indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iATRBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Average True Range indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iATR indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iATRBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iATR indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
1569
Technical Indicators
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1570
Technical Indicators
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iBearsPower.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iBearsPower"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrSilver
1571
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iBearsPower,
// use iBearsPower
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iBearsPower;
input int
ma_period=13;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iBearsPowerBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iBearsPowerBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iBearsPower)
handle=iBearsPower(name,period,ma_period);
else
{
//--- fill the structure with parameters of the indicator
1572
Technical Indicators
MqlParam pars[1];
//--- period of ma
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
handle=IndicatorCreate(name,period,IND_BEARS,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iBearsPower indicator for the symbol %s/%s, error
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Bears Power indicator is calculated for
short_name=StringFormat("iBearsPower(%s/%s, period=%d)",name,EnumToString(period),ma_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iBearsPower indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iB
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
1573
Technical Indicators
{
//--- if the iBearsPowerBuffer array is greater than the number of values in the iBearsPower
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iBearsPowerBuffer array with values of the Bears Power indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iBearsPowerBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Bears Power indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iBearsPower indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iBearsPowerBuffer array with values from the indicator buffer that has 0 i
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBearsPower indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
1574
Technical Indicators
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1575
Technical Indicators
iBands
The function returns the handle of the Bollinger Bands indicator.
int iBands(
string
symbol,
// symbol name
ENUM_TIMEFRAMES
period,
// period
int
bands_period,
int
bands_shift,
double
deviation,
ENUM_APPLIED_PRICE applied_price
);
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.
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.
Return 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
The buffer numbers are the following: 0 - BASE_LINE, 1 - UPPER_BAND, 2 - LOWER_BAND
Example:
//+------------------------------------------------------------------+
//|
Demo_iBands.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
1576
Technical Indicators
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots
"Upper"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrMediumSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Lower"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrMediumSeaGreen
#property indicator_style2
STYLE_SOLID
#property indicator_width2
"Middle"
#property indicator_type3
DRAW_LINE
#property indicator_color3
clrMediumSeaGreen
#property indicator_style3
STYLE_SOLID
#property indicator_width3
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iBands,
// use iBands
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iBands;
input int
bands_period=20;
input int
bands_shift=0;
// shift
input double
deviation=2.0;
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
UpperBuffer[];
double
LowerBuffer[];
1577
Technical Indicators
double
MiddleBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,UpperBuffer,INDICATOR_DATA);
SetIndexBuffer(1,LowerBuffer,INDICATOR_DATA);
SetIndexBuffer(2,MiddleBuffer,INDICATOR_DATA);
//--- set shift of each line
PlotIndexSetInteger(0,PLOT_SHIFT,bands_shift);
PlotIndexSetInteger(1,PLOT_SHIFT,bands_shift);
PlotIndexSetInteger(2,PLOT_SHIFT,bands_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iBands)
handle=iBands(name,period,bands_period,bands_shift,deviation,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period of ma
pars[0].type=TYPE_INT;
pars[0].integer_value=bands_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=bands_shift;
//--- number of standard deviation
pars[2].type=TYPE_DOUBLE;
pars[2].double_value=deviation;
1578
Technical Indicators
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_BANDS,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iBands indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Bollinger Bands indicator is calculated for
short_name=StringFormat("iBands(%s/%s, %d,%d,%G,%s)",name,EnumToString(period),
bands_period,bands_shift,deviation,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iBands indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iB
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
1579
Technical Indicators
{
//--- if the size of indicator buffers is greater than the number of values in the iBands ind
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the Bollinger Bands indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(MiddleBuffer,UpperBuffer,LowerBuffer,bands_shift,handle,values_to_copy
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Bollinger Bands indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iBands indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &base_values[],
double &upper_values[],
double &lower_values[],
int shift,
// shift
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the MiddleBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-shift,amount,base_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBands indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
1580
Technical Indicators
//--- fill a part of the UpperBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,-shift,amount,upper_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBands indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the LowerBuffer array with values from the indicator buffer that has index 2
if(CopyBuffer(ind_handle,2,-shift,amount,lower_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBands indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1581
Technical Indicators
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iBullsPower.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iBullsPower"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrSilver
1582
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iBullsPower,
// use iBullsPower
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iBullsPower;
input int
ma_period=13;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iBullsPowerBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iBullsPowerBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iBullsPower)
handle=iBullsPower(name,period,ma_period);
else
{
//--- fill the structure with parameters of the indicator
1583
Technical Indicators
MqlParam pars[1];
//--- period of ma
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
handle=IndicatorCreate(name,period,IND_BULLS,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iBullsPower indicator for the symbol %s/%s, error
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Bulls Power indicator is calculated for
short_name=StringFormat("iBullsPower(%s/%s, period=%d)",name,EnumToString(period),ma_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iBullsPower indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iB
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
1584
Technical Indicators
{
//--- if the iBullsPowerBuffer array is greater than the number of values in the iBullsPower
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iBullsPowerBuffer array with values of the Bulls Power indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iBullsPowerBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Bulls Power indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iBullsPower indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iBullsPowerBuffer array with values from the indicator buffer that has 0 i
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBullsPower indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
1585
Technical Indicators
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
//+------------------------------------------------------------------+
1586
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iCCI.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
1587
Technical Indicators
#property indicator_plots
"iCCI"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
-100.0
#property indicator_level2
100.0
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iCCI,
// use iCCI
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iCCI;
input int
ma_period=14;
input ENUM_APPLIED_PRICE
applied_price=PRICE_TYPICAL;
// type of price
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iCCIBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iCCIBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
1588
Technical Indicators
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iCCI)
handle=iCCI(name,period,ma_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- type of price
pars[1].type=TYPE_INT;
pars[1].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_CCI,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iCCI indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the CCI indicator is calculated for
short_name=StringFormat("iCCI(%s/%s, %d, %s)",name,EnumToString(period),
ma_period,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
1589
Technical Indicators
{
//--- number of values copied from the iCCI indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iC
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iCCIBuffer array is greater than the number of values in the iCCI indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iCCIBuffer array with values of the Commodity Channel Index indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iCCIBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Commodity Channel Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iCCI indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
1590
Technical Indicators
ResetLastError();
//--- fill a part of the iCCIBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iCCI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1591
Technical Indicators
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_volume
// 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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iChaikin.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1592
Technical Indicators
#property description "of indicator buffers for the iChaikin technical indicator."
#property description "A symbol and timeframe used for calculation of the indicator,"
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iChaikin"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iChaikin,
// use iChaikin
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iChaikin;
input int
fast_ma_period=3;
// period of fast ma
input int
slow_ma_period=10;
// period of slow ma
input ENUM_MA_METHOD
ma_method=MODE_EMA;
// type of smoothing
input ENUM_APPLIED_VOLUME
applied_volume=VOLUME_TICK;
// type of volume
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iChaikinBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iChaikinBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
1593
Technical Indicators
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iChaikin)
handle=iChaikin(name,period,fast_ma_period,slow_ma_period,ma_method,applied_volume);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period of fast ma
pars[0].type=TYPE_INT;
pars[0].integer_value=fast_ma_period;
//--- period of slow ma
pars[1].type=TYPE_INT;
pars[1].integer_value=slow_ma_period;
//--- type of smoothing
pars[2].type=TYPE_INT;
pars[2].integer_value=ma_method;
//--- type of volume
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_volume;
handle=IndicatorCreate(name,period,IND_CHAIKIN,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iChaikin indicator for the symbol %s/%s, error co
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Chaikin Oscillator indicator is calculated for
short_name=StringFormat("iChaikin(%s/%s, %d, %d, %s, %s)",name,EnumToString(period),
fast_ma_period,slow_ma_period,
EnumToString(ma_method),EnumToString(applied_volume));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
1594
Technical Indicators
//+------------------------------------------------------------------+
//| 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[])
{
//--- number of values copied from the iChaikin indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iC
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iChaikinBuffer array is greater than the number of values in the iChaikin indica
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iChaikinBuffer array with values of the Chaikin Oscillator indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iChaikinBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Chaikin Oscillator indicator
1595
Technical Indicators
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iChaikin indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iChaikinBuffer array with values from the indicator buffer that has 0 inde
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iChaikin indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1596
Technical Indicators
iCustom
The function returns the handle of a specified custom indicator.
int iCustom(
string
symbol,
// symbol name
ENUM_TIMEFRAMES period,
// period
string
// folder/custom_indicator_name
...
name
);
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.
Return 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:
#property tester_indicator "indicator_name.ex5"
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.
1597
Technical Indicators
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
"Label1"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
Label1Buffer[];
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
ResetLastError();
MA_handle=iCustom(NULL,0,"Examples\\Custom Moving Average",
MA_Period,
1598
Technical Indicators
MA_Shift,
MA_Method,
PRICE_CLOSE // using the close prices
);
Print("MA_handle = ",MA_handle,"
error = ",GetLastError());
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- 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);
1599
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iDEMA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1600
Technical Indicators
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iDEMA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iDEMA,
// use iDEMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iDEMA;
// type of te function
input int
ma_period=14;
input int
ma_shift=0;
// shift
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iDEMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iDEMABuffer,INDICATOR_DATA);
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
1601
Technical Indicators
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iDEMA)
handle=iDEMA(name,period,ma_period,ma_shift,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[3];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of price
pars[2].type=TYPE_INT;
pars[2].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_DEMA,3,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iDEMA indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Double Exponential Moving Average indicator is calculated for
short_name=StringFormat("iDEMA(%s/%s, %d, %d, %s)",name,EnumToString(period),
ma_period,ma_shift,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
1602
Technical Indicators
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[])
{
//--- number of values copied from the iDEMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iD
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iDEMABuffer array is greater than the number of values in the iDEMA indicator fo
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iDEMABuffer array with values of the Double Exponential Moving Average indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iDEMABuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Double Exponential Moving Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
1603
Technical Indicators
//| Filling indicator buffers from the iDEMA indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int shift,
// shift
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iDEMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-shift,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iDEMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1604
Technical Indicators
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
// averaging period
ma_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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iDeMarker.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iDeMarker"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
1605
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
0.3
#property indicator_level2
0.7
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iDeMarker,
// use iDeMarker
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iDeMarker;
input int
ma_period=14;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iDeMarkerBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iDeMarkerBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iDeMarker)
handle=iDeMarker(name,period,ma_period);
1606
Technical Indicators
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
handle=IndicatorCreate(name,period,IND_DEMARKER,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iDeMarker indicator for the symbol %s/%s, error c
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the DeMarker indicator is calculated for
short_name=StringFormat("iDeMarker(%s/%s, period=%d)",name,EnumToString(period),ma_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iDeMarker indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
1607
Technical Indicators
//--- if it is the first start of calculation of the indicator or if the number of values in the iD
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iDeMarkerBuffer array is greater than the number of values in the iDeMarker indi
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iDeMarkerBuffer array with values of the DeMarker indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iDeMarkerBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the DeMarker indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iDeMarker indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iDeMarkerBuffer array with values from the indicator buffer that has 0 ind
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iDeMarker indicator, error code %d",GetLastError())
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
1608
Technical Indicators
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1609
Technical Indicators
iEnvelopes
The function returns the handle of the Envelopes indicator.
int iEnvelopes(
string
symbol,
// symbol name
ENUM_TIMEFRAMES
period,
// period
int
ma_period,
int
ma_shift,
ENUM_MA_METHOD
ma_method,
// type of smoothing
ENUM_APPLIED_PRICE applied_price,
double
deviation
);
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.
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).
Return 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
The buffer numbers: 0 - UPPER_LINE, 1 - LOWER_LINE.
Example:
//+------------------------------------------------------------------+
1610
Technical Indicators
//|
Demo_iEnvelopes.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
"Upper"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Lower"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iEnvelopes,
// use iEnvelopes
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iEnvelopes;
input int
ma_period=14;
input int
ma_shift=0;
// shift
input ENUM_MA_METHOD
ma_method=MODE_SMA;
// type of smoothing
input ENUM_APPLIED_PRICE
input double
deviation=0.1;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
UpperBuffer[];
double
LowerBuffer[];
1611
Technical Indicators
int
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,UpperBuffer,INDICATOR_DATA);
SetIndexBuffer(1,LowerBuffer,INDICATOR_DATA);
//--- set shift of each line
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
PlotIndexSetInteger(1,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iEnvelopes)
handle=iEnvelopes(name,period,ma_period,ma_shift,ma_method,applied_price,deviation);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[5];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of smoothing
pars[2].type=TYPE_INT;
pars[2].integer_value=ma_method;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
//--- type of price
1612
Technical Indicators
pars[4].type=TYPE_DOUBLE;
pars[4].double_value=deviation;
handle=IndicatorCreate(name,period,IND_ENVELOPES,5,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iEnvelopes indicator for the symbol %s/%s, error
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Envelopes indicator is calculated for
short_name=StringFormat("iEnvelopes(%s/%s, %d, %d, %s,%s, %G)",name,EnumToString(period),
ma_period,ma_shift,EnumToString(ma_method),EnumToString(applied_price),deviation);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iEnvelopes indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iE
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
1613
Technical Indicators
//--- if the UpperBuffer array is greater than the number of values in the iEnvelopes indicat
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the UpperBuffer and LowerBuffer arrays with values from the Envelopes indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArraysFromBuffers(UpperBuffer,LowerBuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Envelopes indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iEnvelopes indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &upper_values[],
double &lower_values[],
int shift,
// shift
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the UpperBuffer array with values from the indicator buffer that has index 0
if(CopyBuffer(ind_handle,0,-shift,amount,upper_values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iEnvelopes indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the LowerBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,-shift,amount,lower_values)<0)
{
1614
Technical Indicators
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iEnvelopes indicator, error code %d",GetLastError()
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1615
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iForce.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
1616
Technical Indicators
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iForce"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iForce,
// use iForce
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iForce;
input int
ma_period=13;
// period of averaging
input ENUM_MA_METHOD
ma_method=MODE_SMA;
// type of smoothing
input ENUM_APPLIED_VOLUME
applied_volume=VOLUME_TICK;
// type of volume
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iForceBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iForceBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
1617
Technical Indicators
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iForce)
handle=iForce(name,period,ma_period,ma_method,applied_volume);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[3];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- type of smoothing
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_method;
//--- type of volume
pars[2].type=TYPE_INT;
pars[2].integer_value=applied_volume;
//--- type of price
handle=IndicatorCreate(name,period,IND_FORCE,3,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iForce indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Force indicator is calculated for
short_name=StringFormat("iForce(%s/%s, %d, %s, %s)",name,EnumToString(period),
ma_period,EnumToString(ma_method),EnumToString(applied_volume));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
1618
Technical Indicators
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iForce indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iF
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iForceBuffer array is greater than the number of values in the iForce indicator
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iForceBuffer array with values of the Force indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iForceBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Force indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iForce indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
1619
Technical Indicators
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iForceBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iForce indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1620
Technical Indicators
iFractals
The function returns the handle of the Fractals indicator.
int iFractals(
string
symbol,
ENUM_TIMEFRAMES period
// symbol name
// 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.
Return 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
The buffer numbers are the following: 0 - UPPER_LINE, 1 - LOWER_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iFractals.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots
1621
Technical Indicators
#property indicator_label1
"FractalUp"
#property indicator_type1
DRAW_ARROW
#property indicator_color1
clrBlue
"FractalDown"
#property indicator_type2
DRAW_ARROW
#property indicator_color2
clrRed
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iFractals,
// use iFractals
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iFractals;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
FractalUpBuffer[];
double
FractalDownBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,FractalUpBuffer,INDICATOR_DATA);
SetIndexBuffer(1,FractalDownBuffer,INDICATOR_DATA);
//--- set codes using a symbol from the Wingdings charset for the PLOT_ARROW property
PlotIndexSetInteger(0,PLOT_ARROW,217); // arrow up
PlotIndexSetInteger(1,PLOT_ARROW,218); // arrow down
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
1622
Technical Indicators
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iFractals)
handle=iFractals(name,period);
else
handle=IndicatorCreate(name,period,IND_FRACTALS);
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iFractals indicator for the symbol %s/%s, error c
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Fractals indicator is calculated for
short_name=StringFormat("iFractals(%s/%s)",name,EnumToString(period));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iFractals indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iF
1623
Technical Indicators
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the FractalUpBuffer array is greater than the number of values in the iFractals indi
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the FractalUpBuffer and FractalDownBuffer arrays with values from the Fractals indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArraysFromBuffers(FractalUpBuffer,FractalDownBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Fractals indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iFractals indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &up_arrows[],
double &down_arrows[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the FractalUpBuffer array with values from the indicator buffer that has 0 ind
if(CopyBuffer(ind_handle,0,0,amount,up_arrows)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iFractals indicator to the FractalUpBuffer array, e
GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
1624
Technical Indicators
//--- fill a part of the FractalDownBuffer array with values from the indicator buffer that has ind
if(CopyBuffer(ind_handle,1,0,amount,down_arrows)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iFractals indicator to the FractalDownBuffer array,
GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1625
Technical Indicators
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,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iFrAMA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1626
Technical Indicators
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iFrAMA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iFrAMA,
// use iFrAMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iFrAMA;
input int
ma_period=14;
// period of averaging
input int
ma_shift=0;
// shift
input ENUM_APPLIED_PRICE
applied_price=PRICE_CLOSE;
// type of price
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iFrAMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iFrAMABuffer,INDICATOR_DATA);
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
1627
Technical Indicators
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iFrAMA)
handle=iFrAMA(name,period,ma_period,ma_shift,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[3];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of price
pars[2].type=TYPE_INT;
pars[2].integer_value=applied_price;
//--- type of price
handle=IndicatorCreate(name,period,IND_FRAMA,3,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iFrAMA indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the iFrAMA indicator is calculated for
short_name=StringFormat("iFrAMA(%s/%s, %d, %d, %s)",name,EnumToString(period),
ma_period,ma_shift,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
1628
Technical Indicators
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[])
{
//--- number of values copied from the iFrAMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iF
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iFrAMABuffer array is greater than the number of values in the iFrAMA indicator
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iFrAMABuffer array with values of the Fractal Adaptive Moving Average indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iFrAMABuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Fractal Adaptive Moving Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
1629
Technical Indicators
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iFrAMA indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int shift,
// shift
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iFrAMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-shift,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iFrAMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1630
Technical Indicators
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,
int
jaw_shift,
int
teeth_period,
int
teeth_shift,
int
lips_period,
int
lips_shift,
ENUM_MA_METHOD
ma_method,
// type of smoothing
ENUM_APPLIED_PRICE applied_price
);
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.
1631
Technical Indicators
applied_price
[in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of
another indicator.
Return 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
Buffer numbers: 0 - UPPER_HISTOGRAM, 1 - color buffer of the upper histogram, 2 LOWER_HISTOGRAM, 3 - color buffer of the lower histogram.
Example:
//+------------------------------------------------------------------+
//|
Demo_iGator.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All other parameters are as in a standard Gator Oscillator."
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots
"GatorUp"
#property indicator_type1
DRAW_COLOR_HISTOGRAM
#property indicator_color1
clrGreen, clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"GatorDown"
#property indicator_type2
DRAW_COLOR_HISTOGRAM
#property indicator_color2
clrGreen, clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
1632
Technical Indicators
{
Call_iGator,
// use iGator
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iGator;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
input int
jaw_period=13;
input int
jaw_shift=8;
input int
teeth_period=8;
input int
teeth_shift=5;
input int
lips_period=5;
input int
lips_shift=3;
input ENUM_MA_METHOD
MA_method=MODE_SMMA;
input ENUM_APPLIED_PRICE
GatorUpBuffer[];
double
GatorUpColors[];
double
GatorDownBuffer[];
double
GatorDownColors[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,GatorUpBuffer,INDICATOR_DATA);
SetIndexBuffer(1,GatorUpColors,INDICATOR_COLOR_INDEX);
SetIndexBuffer(2,GatorDownBuffer,INDICATOR_DATA);
SetIndexBuffer(3,GatorDownColors,INDICATOR_COLOR_INDEX);
/*
All the shifts specified in the parameters refer to the Alligator indicator on the basis which th
That's is why they don't move the Gator indicator itself, but they move the Alligator lines,
which values are used for calculation of the Gator Oscillator!
*/
//--- let's calculate the shift for the upper and lower histograms, that is equal to the difference
shift=MathMin(jaw_shift,teeth_shift);
PlotIndexSetInteger(0,PLOT_SHIFT,shift);
1633
Technical Indicators
//--- despite the indicator contains two histograms, the same shift is used - this is the implement
PlotIndexSetInteger(1,PLOT_SHIFT,shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iGator)
handle=iGator(name,period,jaw_period,jaw_shift,teeth_period,teeth_shift,
lips_period,lips_shift,MA_method,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[8];
//--- periods and shifts of the Alligator lines
pars[0].type=TYPE_INT;
pars[0].integer_value=jaw_period;
pars[1].type=TYPE_INT;
pars[1].integer_value=jaw_shift;
pars[2].type=TYPE_INT;
pars[2].integer_value=teeth_period;
pars[3].type=TYPE_INT;
pars[3].integer_value=teeth_shift;
pars[4].type=TYPE_INT;
pars[4].integer_value=lips_period;
pars[5].type=TYPE_INT;
pars[5].integer_value=lips_shift;
//--- type of smoothing
pars[6].type=TYPE_INT;
pars[6].integer_value=MA_method;
//--- type of price
pars[7].type=TYPE_INT;
pars[7].integer_value=applied_price;
//--- create handle
handle=IndicatorCreate(name,period,IND_GATOR,8,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iGator indicator for the symbol %s/%s, error code
1634
Technical Indicators
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Gator Oscillator indicator is calculated for
short_name=StringFormat("iGator(%s/%s, %d, %d ,%d, %d, %d, %d)",name,EnumToString(period),
jaw_period,jaw_shift,teeth_period,teeth_shift,lips_period,lips_shift);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iGator indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iG
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the GatorUpBuffer array is greater than the number of values in the iGator indicator
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
1635
Technical Indicators
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the Gator Oscillator indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(GatorUpBuffer,GatorUpColors,GatorDownBuffer,GatorDownColors,
shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Gator Oscillator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iGator indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &ups_buffer[],
double &up_color_buffer[],
double &downs_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the GatorUpBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-u_shift,amount,ups_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iGator indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the GatorUpColors array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,-u_shift,amount,up_color_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iGator indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
1636
Technical Indicators
//--- fill a part of the GatorDownBuffer array with values from the indicator buffer that has index
if(CopyBuffer(ind_handle,2,-u_shift,amount,downs_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iGator indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the GatorDownColors array with values from the indicator buffer that has index
if(CopyBuffer(ind_handle,3,-u_shift,amount,downs_color_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iGator indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1637
Technical Indicators
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
);
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.
Return 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
The buffer numbers: 0 - TENKANSEN_LINE, 1 - KIJUNSEN_LINE, 2 - SENKOUSPANA_LINE, 3 SENKOUSPANB_LINE, 4 - CHIKOUSPAN_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iIchimoku.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1638
Technical Indicators
#property description "of indicator buffers for the iIchimoku technical indicator."
#property description "A symbol and timeframe used for calculation of the indicator,"
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All other parameters just like in the standard Ichimoku Kinko Hyo."
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots
"Tenkan_sen"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Kijun_sen"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrBlue
#property indicator_style2
STYLE_SOLID
#property indicator_width2
"Senkou Span A;Senkou Span B" // two fields will be shown in Data Windo
#property indicator_type3
DRAW_FILLING
#property indicator_color3
clrSandyBrown, clrThistle
#property indicator_style3
STYLE_SOLID
#property indicator_width3
"Chinkou_Span"
#property indicator_type4
DRAW_LINE
#property indicator_color4
clrLime
#property indicator_style4
STYLE_SOLID
#property indicator_width4
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iIchimoku,
// use iIchimoku
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iIchimoku;
input int
tenkan_sen=9;
// period of Tenkan-sen
input int
kijun_sen=26;
// period of Kijun-sen
input int
senkou_span_b=52;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
1639
Technical Indicators
double
Tenkan_sen_Buffer[];
double
Kijun_sen_Buffer[];
double
Senkou_Span_A_Buffer[];
double
Senkou_Span_B_Buffer[];
double
Chinkou_Span_Buffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,Tenkan_sen_Buffer,INDICATOR_DATA);
SetIndexBuffer(1,Kijun_sen_Buffer,INDICATOR_DATA);
SetIndexBuffer(2,Senkou_Span_A_Buffer,INDICATOR_DATA);
SetIndexBuffer(3,Senkou_Span_B_Buffer,INDICATOR_DATA);
SetIndexBuffer(4,Chinkou_Span_Buffer,INDICATOR_DATA);
//--- set the shift for the Senkou Span channel of kijun_sen bars in the future direction
PlotIndexSetInteger(2,PLOT_SHIFT,kijun_sen);
//--- setting a shift for the Chikou Span line is not required, since the Chinkou data Span
//--- is already stored with a shift in iIchimoku
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iIchimoku)
handle=iIchimoku(name,period,tenkan_sen,kijun_sen,senkou_span_b);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[3];
//--- periods and shifts of the Alligator lines
pars[0].type=TYPE_INT;
pars[0].integer_value=tenkan_sen;
1640
Technical Indicators
pars[1].type=TYPE_INT;
pars[1].integer_value=kijun_sen;
pars[2].type=TYPE_INT;
pars[2].integer_value=senkou_span_b;
//--- create handle
handle=IndicatorCreate(name,period,IND_ICHIMOKU,3,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iIchimoku indicator for the symbol %s/%s, error c
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Ichimoku Kinko Hyo indicator is calculated for
short_name=StringFormat("iIchimoku(%s/%s, %d, %d ,%d)",name,EnumToString(period),
tenkan_sen,kijun_sen,senkou_span_b);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iIchimoku indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iI
1641
Technical Indicators
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the Tenkan_sen_Buffer array is greater than the number of values in the iIchimoku in
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the Ichimoku Kinko Hyo indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(Tenkan_sen_Buffer,Kijun_sen_Buffer,Senkou_Span_A_Buffer,Senkou_Span_B_
kijun_sen,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Ichimoku Kinko Hyo indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iIchimoku indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &tenkan_sen_buffer[],
double &kijun_sen_buffer[],
double &senkou_span_A_buffer[],
double &senkou_span_B_buffer[],
double &chinkou_span_buffer[],
int senkou_span_shift,
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the Tenkan_sen_Buffer array with values from the indicator buffer that has 0 i
if(CopyBuffer(ind_handle,0,0,amount,tenkan_sen_buffer)<0)
{
//--- if the copying fails, tell the error code
1642
Technical Indicators
PrintFormat("1.Failed to copy data from the iIchimoku indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the Kijun_sen_Buffer array with values from the indicator buffer that has inde
if(CopyBuffer(ind_handle,1,0,amount,kijun_sen_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("2.Failed to copy data from the iIchimoku indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the Chinkou_Span_Buffer array with values from the indicator buffer that has i
//--- if senkou_span_shift>0, the line is shifted in the future direction by senkou_span_shift bars
if(CopyBuffer(ind_handle,2,-senkou_span_shift,amount,senkou_span_A_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("3.Failed to copy data from the iIchimoku indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the Senkou_Span_A_Buffer array with values from the indicator buffer that has
//--- if senkou_span_shift>0, the line is shifted in the future direction by senkou_span_shift bars
if(CopyBuffer(ind_handle,3,-senkou_span_shift,amount,senkou_span_B_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("4.Failed to copy data from the iIchimoku indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the Senkou_Span_B_Buffer array with values from the indicator buffer that has
//--- when copying Chinkou Span, we don't need to consider the shift, since the Chinkou Span data
//--- is already stored with a shift in iIchimoku
if(CopyBuffer(ind_handle,4,0,amount,chinkou_span_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("5.Failed to copy data from the iIchimoku indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
1643
Technical Indicators
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1644
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iBWMFI.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"iBWMFI"
#property indicator_type1
DRAW_COLOR_HISTOGRAM
#property indicator_color1
clrLime,clrSaddleBrown,clrBlue,clrPink
1645
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iBWMFI,
// use iBWMFI
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iBWMFI;
// type of function
input ENUM_APPLIED_VOLUME
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iBWMFIBuffer[];
double
iBWMFIColors[];
handle;
//--- we will keep the number of values in the Market Facilitation Index by Bill Williams indicator
int
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,iBWMFIBuffer,INDICATOR_DATA);
SetIndexBuffer(1,iBWMFIColors,INDICATOR_COLOR_INDEX);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iBWMFI)
handle=iBWMFI(name,period,applied_volume);
else
1646
Technical Indicators
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
//--- type of volume
pars[0].type=TYPE_INT;
pars[0].integer_value=applied_volume;
handle=IndicatorCreate(name,period,IND_BWMFI,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iBWMFI indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Market Facilitation Index by Bill Williams indicator is calcula
short_name=StringFormat("iBWMFI(%s/%s, %s)",name,EnumToString(period),
EnumToString(applied_volume));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iBWMFI indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
1647
Technical Indicators
//--- if it is the first start of calculation of the indicator or if the number of values in the iB
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iBWMFIBuffer array is greater than the number of values in the iBWMFI indicator
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the indicator Market Facilitation Index by Bill Williams
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(iBWMFIBuffer,iBWMFIColors,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Market Facilitation Index by Bill Williams indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iBWMFI indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &values[],
double &colors[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iBWMFIBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBWMFI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
1648
Technical Indicators
//--- fill a part of the iBWMFIColors array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,0,amount,colors)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iBWMFI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1649
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iMomentum.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Momentum."
#property indicator_separate_window
1650
Technical Indicators
#property indicator_buffers 1
#property indicator_plots
"iMomentum"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrDodgerBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iMomentum,
// use iMomentum
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iMomentum;
input int
mom_period=14;
// period of Momentum
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iMomentumBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iMomentumBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
1651
Technical Indicators
}
//--- create handle of the indicator
if(type==Call_iMomentum)
handle=iMomentum(name,period,mom_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=mom_period;
//--- type of price
pars[1].type=TYPE_INT;
pars[1].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_MOMENTUM,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iMomentum indicator for the symbol %s/%s, error c
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Momentum indicator is calculated for
short_name=StringFormat("iMomentum(%s/%s, %d, %s)",name,EnumToString(period),
mom_period, EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iMomentum indicator
1652
Technical Indicators
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iM
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iMomentumBuffer array is greater than the number of values in the iMomentum indi
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iMomentumBuffer array with values of the Momentum indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iMomentumBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Momentum indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iMomentum indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iMomentumBuffer array with values from the indicator buffer that has 0 ind
1653
Technical Indicators
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iMomentum indicator, error code %d",GetLastError())
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1654
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iMFI.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Money Flow Index."
#property indicator_separate_window
#property indicator_buffers 1
1655
Technical Indicators
#property indicator_plots
"iMFI"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrDodgerBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
20
#property indicator_level2
80
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iMFI,
// use iMFI
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iMFI;
input int
ma_period=14;
// period
input ENUM_APPLIED_VOLUME
applied_volume=VOLUME_TICK;
// type of volume
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iMFIBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iMFIBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
1656
Technical Indicators
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iMFI)
handle=iMFI(name,period,ma_period,applied_volume);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- type of volume
pars[1].type=TYPE_INT;
pars[1].integer_value=applied_volume;
handle=IndicatorCreate(name,period,IND_MFI,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iMFI indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Money Flow Index indicator is calculated for
short_name=StringFormat("iMFI(%s/%s, %d, %s)",name,EnumToString(period),
ma_period, EnumToString(applied_volume));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
1657
Technical Indicators
{
//--- number of values copied from the iMFI indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iM
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iMFIBuffer array is greater than the number of values in the iMFI indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iMFIBuffer array with values of the Money Flow Index indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iMFIBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Money Flow Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iMFI indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int ind_handle,
int amount
)
{
//--- reset error code
1658
Technical Indicators
ResetLastError();
//--- fill a part of the iMFIBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iMFI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1659
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iMA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1660
Technical Indicators
#property description "The indicator demonstrates how to obtain data"
#property description "of indicator buffers for the iMA technical indicator."
#property description "A symbol and timeframe used for calculation of the indicator,"
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All other parameters like in the standard Moving Average."
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iMA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iMA,
// use iMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iMA;
input int
ma_period=10;
// period of ma
input int
ma_shift=0;
// shift
input ENUM_MA_METHOD
ma_method=MODE_SMA;
// type of smoothing
input ENUM_APPLIED_PRICE
applied_price=PRICE_CLOSE;
// type of price
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iMABuffer,INDICATOR_DATA);
1661
Technical Indicators
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iMA)
handle=iMA(name,period,ma_period,ma_shift,ma_method,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of smoothing
pars[2].type=TYPE_INT;
pars[2].integer_value=ma_method;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_MA,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Moving Average indicator is calculated for
short_name=StringFormat("iMA(%s/%s, %d, %d, %s, %s)",name,EnumToString(period),
ma_period, ma_shift,EnumToString(ma_method),EnumToString(applied_price))
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
1662
Technical Indicators
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iM
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iMABuffer array is greater than the number of values in the iMA indicator for sy
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the iMABuffer array with values of the Moving Average indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iMABuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
1663
Technical Indicators
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Moving Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the MA indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],
int shift,
// shift
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-shift,amount,values)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1664
Technical Indicators
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,
int
slow_ema_period,
int
signal_period,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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
In some systems this oscillator is also known as MACD histogram.
Example:
//+------------------------------------------------------------------+
//|
Demo_iOsMA.mq5 |
//|
//|
https://www.mql5.com |
1665
Technical Indicators
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Moving Average of Oscil
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iOsMA"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrSilver
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iOsMA,
// use iOsMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iOsMA;
input int
fast_ema_period=12;
// period of fast ma
input int
slow_ema_period=26;
// period of slow ma
input int
signal_period=9;
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iOsMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
1666
Technical Indicators
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iOsMABuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iOsMA)
handle=iOsMA(name,period,fast_ema_period,slow_ema_period,signal_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period of fast ma
pars[0].type=TYPE_INT;
pars[0].integer_value=fast_ema_period;
//--- period of slow ma
pars[1].type=TYPE_INT;
pars[1].integer_value=slow_ema_period;
//--- period of averaging of difference between the fast and the slow moving average
pars[2].type=TYPE_INT;
pars[2].integer_value=signal_period;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_OSMA,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create a handle of iOsMA for the pair %s/%s, error code is %d",
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Moving Average of Oscillator indicator is calculated for
short_name=StringFormat("iOsMA(%s/%s,%d,%d,%d,%s)",name,EnumToString(period),
1667
Technical Indicators
fast_ema_period,slow_ema_period,signal_period,EnumToString(applied_price
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iOsMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iO
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iOsMABuffer array is greater than the number of values in the iOsMA indicator fo
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iOsMA indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iOsMABuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
1668
Technical Indicators
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Moving Average of Oscillator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iOsMA indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &ama_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iOsMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,ama_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iOsMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1669
Technical Indicators
iMACD
The function returns the handle of the Moving Averages Convergence/Divergence indicator. In systems
where OsMA 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,
int
slow_ema_period,
int
signal_period,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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
The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iMACD.mq5 |
//|
1670
Technical Indicators
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All other parameters like in the standard MACD."
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"MACD"
#property indicator_type1
DRAW_HISTOGRAM
#property indicator_color1
clrSilver
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Signal"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrRed
#property indicator_style2
STYLE_DOT
#property indicator_width2
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iMACD,
// use iMACD
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iMACD;
input int
fast_ema_period=12;
// period of fast ma
input int
slow_ema_period=26;
// period of slow ma
input int
signal_period=9;
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
MACDBuffer[];
double
SignalBuffer[];
handle;
1671
Technical Indicators
string name=symbol;
//--- name of the indicator on a chart
string short_name;
//--- we will keep the number of values in the Moving Averages Convergence/Divergence indicator
int
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,MACDBuffer,INDICATOR_DATA);
SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iMACD)
handle=iMACD(name,period,fast_ema_period,slow_ema_period,signal_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period of fast ma
pars[0].type=TYPE_INT;
pars[0].integer_value=fast_ema_period;
//--- period of slow ma
pars[1].type=TYPE_INT;
pars[1].integer_value=slow_ema_period;
//--- period of averaging of difference between the fast and the slow moving average
pars[2].type=TYPE_INT;
pars[2].integer_value=signal_period;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_MACD,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
1672
Technical Indicators
PrintFormat("Failed to create handle of the iMACD indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Moving Average Convergence/Divergence indicator is calculated f
short_name=StringFormat("iMACD(%s/%s,%d,%d,%d,%s)",name,EnumToString(period),
fast_ema_period,slow_ema_period,signal_period,EnumToString(applied_price
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iMACD indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iM
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the MACDBuffer array is greater than the number of values in the iMACD indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
1673
Technical Indicators
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iMACD indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(MACDBuffer,SignalBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in theMoving Averages indicator Convergence/Divergence
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iMACD indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &macd_buffer[],
double &signal_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iMACDBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,macd_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iMACD indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the SignalBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,0,amount,signal_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iMACD indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
1674
Technical Indicators
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1675
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iOBV.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
//---
iOBV
#property indicator_label1
"iOBV"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
1676
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iOBV ,
// use iOBV
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iOBV;
input ENUM_APPLIED_VOLUME
applied_volume=VOLUME_TICK;
// type of volume
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iOBVBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iOBVBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iOBV)
handle=iOBV(name,period,applied_volume);
else
{
//--- fill the structure with parameters of the indicator
1677
Technical Indicators
MqlParam pars[1];
//--- type of volume
pars[0].type=TYPE_INT;
pars[0].integer_value=applied_volume;
handle=IndicatorCreate(name,period,IND_OBV,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iOBV indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the On Balance Volume indicator is calculated for
short_name=StringFormat("iOBV(%s/%s, %s)",name,EnumToString(period),
EnumToString(applied_volume));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iOBV indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iO
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
1678
Technical Indicators
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iOBVBuffer array is greater than the number of values in the iOBV indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iOBV indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iOBVBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the On Balance Volume indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iOBV indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &obv_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iOBVBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,obv_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iOBV indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
1679
Technical Indicators
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1680
Technical Indicators
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,
double
maximum
);
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 step of price increment, usually 0.02.
maximum
[in] The maximum step, usually 0.2.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iSAR.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Parabolic Stop and Reve
#property indicator_chart_window
1681
Technical Indicators
#property indicator_buffers 1
#property indicator_plots
"iSAR"
#property indicator_type1
DRAW_ARROW
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iSAR,
// use iSAR
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iSAR;
input double
step=0.02;
input double
maximum=0.2;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iSARBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iSARBuffer,INDICATOR_DATA);
//--- set a symbol code from the Wingdings charset for the PLOT_ARROW property for displaying on a
PlotIndexSetInteger(0,PLOT_ARROW,159);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
1682
Technical Indicators
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iSAR)
handle=iSAR(name,period,step,maximum);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- step value
pars[0].type=TYPE_DOUBLE;
pars[0].double_value=step;
//--- limit of the step value that can be used for calculations
pars[1].type=TYPE_DOUBLE;
pars[1].double_value=maximum;
handle=IndicatorCreate(name,period,IND_SAR,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iSAR indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Parabolic SAR indicator is calculated for
short_name=StringFormat("iSAR(%s/%s, %G, %G)",name,EnumToString(period),
step,maximum);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
1683
Technical Indicators
{
//--- number of values copied from the iSAR indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iS
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iSARBuffer array is greater than the number of values in the iSAR indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iSAR indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iSARBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Parabolic SAR indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iSAR indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &sar_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
1684
Technical Indicators
ResetLastError();
//--- fill a part of the iSARBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,sar_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iSAR indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1685
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iRSI.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Relative Strength Index
#property indicator_separate_window
1686
Technical Indicators
#property indicator_buffers 1
#property indicator_plots
"iRSI"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrDodgerBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
70.0
#property indicator_level2
30.0
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iRSI,
// use iRSI
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iRSI;
input int
ma_period=14;
// period of averaging
input ENUM_APPLIED_PRICE
applied_price=PRICE_CLOSE;
// type of price
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iRSIBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iRSIBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
1687
Technical Indicators
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iRSI)
handle=iRSI(name,period,ma_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- period of moving average
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- limit of the step value that can be used for calculations
pars[1].type=TYPE_INT;
pars[1].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_RSI,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iRSI indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Relative Strength Index indicator is calculated for
short_name=StringFormat("iRSI(%s/%s, %d, %d)",name,EnumToString(period),
ma_period,applied_price);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
1688
Technical Indicators
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iRSI indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iR
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iRSIBuffer array is greater than the number of values in the iRSI indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the iRSI indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iRSIBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Relative Strength Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iRSI indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &rsi_buffer[],
int ind_handle,
1689
Technical Indicators
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iRSIBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,rsi_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iRSI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1690
Technical Indicators
iRVI
The function returns the handle of the Relative Vigor Index indicator.
int iRVI(
string
symbol,
// symbol name
ENUM_TIMEFRAMES period,
// period
int
// averaging period
ma_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.
Return 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
The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iRVI.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Relative Vigor Index."
#property indicator_separate_window
#property indicator_buffers 2
1691
Technical Indicators
#property indicator_plots
"RVI"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Signal"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iRVI,
// use iRVI
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iRVI;
input int
ma_period=10;
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
RVIBuffer[];
double
SignalBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,RVIBuffer,INDICATOR_DATA);
SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
1692
Technical Indicators
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iRVI)
handle=iRVI(name,period,ma_period);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
//--- period for calculations
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
handle=IndicatorCreate(name,period,IND_RVI,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iRVI indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Relative Vigor Index indicator is calculated for
short_name=StringFormat("iRVI(%s/%s, %d, %d)",name,EnumToString(period),ma_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
1693
Technical Indicators
{
//--- number of values copied from the iRVI indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iR
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the RVIBuffer array is greater than the number of values in the iRVI indicator for s
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iRVI indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(RVIBuffer,SignalBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Relative Vigor Index indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iRVI indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &rvi_buffer[],
double &signal_buffer[],
int ind_handle,
int amount
)
{
1694
Technical Indicators
//--- reset error code
ResetLastError();
//--- fill a part of the iRVIBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,rvi_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iRVI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the SignalBuffer array with values from the indicator buffer that has index 1
if(CopyBuffer(ind_handle,1,0,amount,signal_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iRVI indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1695
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iStdDev.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1696
Technical Indicators
#property description "The indicator demonstrates how to obtain data"
#property description "of indicator buffers for the iStdDev technical indicator."
#property description "A symbol and timeframe used for calculation of the indicator,"
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the normal Standard Deviation."
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iStdDev"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrMediumSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iStdDev,
// use iStdDev
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iStdDev;
input int
ma_period=20;
// period of averaging
input int
ma_shift=0;
// shift
input ENUM_MA_METHOD
ma_method=MODE_SMA;
// type of smoothing
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iStdDevBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iStdDevBuffer,INDICATOR_DATA);
1697
Technical Indicators
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iStdDev)
handle=iStdDev(name,period,ma_period,ma_shift,ma_method,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of smoothing
pars[2].type=TYPE_INT;
pars[2].integer_value=ma_method;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_STDDEV,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iStdDev indicator for the symbol %s/%s, error cod
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Standard Deviation indicator is calculated for
short_name=StringFormat("iStdDev(%s/%s, %d, %d, %s, %s)",name,EnumToString(period),
ma_period,ma_shift,EnumToString(ma_method),EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
1698
Technical Indicators
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iStdDev indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iS
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iStdDevBuffer array is greater than the number of values in the iStdDev indicato
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the Standard Deviation indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iStdDevBuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
1699
Technical Indicators
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Standard Deviation indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iStdDev indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &std_buffer[],
int std_shift,
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iStdDevBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-std_shift,amount,std_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iStdDev indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1700
Technical Indicators
iStochastic
The function returns the handle of the Stochastic Oscillator indicator.
int iStochastic(
string
symbol,
// symbol name
ENUM_TIMEFRAMES period,
// period
int
Kperiod,
int
Dperiod,
int
slowing,
// final smoothing
ENUM_MA_METHOD
ma_method,
// type of smoothing
ENUM_STO_PRICE
price_field
);
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.
Return 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
The buffer numbers: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
Example:
//+------------------------------------------------------------------+
//|
Demo_iStochastic.mq5 |
1701
Technical Indicators
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Stochastic Oscillator."
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"Stochastic"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrLightSeaGreen
#property indicator_style1
STYLE_SOLID
#property indicator_width1
"Signal"
#property indicator_type2
DRAW_LINE
#property indicator_color2
clrRed
#property indicator_style2
STYLE_SOLID
#property indicator_width2
-100.0
#property indicator_level2
100.0
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iStochastic,
// use iStochastic
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iStochastic;
input int
Kperiod=5;
input int
Dperiod=3;
input int
slowing=3;
input ENUM_MA_METHOD
ma_method=MODE_SMA;
// type of smoothing
input ENUM_STO_PRICE
price_field=STO_LOWHIGH;
1702
Technical Indicators
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
StochasticBuffer[];
double
SignalBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of arrays to indicator buffers
SetIndexBuffer(0,StochasticBuffer,INDICATOR_DATA);
SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iStochastic)
handle=iStochastic(name,period,Kperiod,Dperiod,slowing,ma_method,price_field);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[5];
//--- the K period for calculations
pars[0].type=TYPE_INT;
pars[0].integer_value=Kperiod;
//--- the D period for primary smoothing
pars[1].type=TYPE_INT;
pars[1].integer_value=Dperiod;
//--- the K period for final smoothing
pars[2].type=TYPE_INT;
pars[2].integer_value=slowing;
//--- type of smoothing
1703
Technical Indicators
pars[3].type=TYPE_INT;
pars[3].integer_value=ma_method;
//--- method of calculation of the Stochastic
pars[4].type=TYPE_INT;
pars[4].integer_value=price_field;
handle=IndicatorCreate(name,period,IND_STOCHASTIC,5,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iStochastic indicator for the symbol %s/%s, error
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Stochastic Oscillator indicator is calculated for
short_name=StringFormat("iStochastic(%s/%s, %d, %d, %d, %s, %s)",name,EnumToString(period),
Kperiod,Dperiod,slowing,EnumToString(ma_method),EnumToString(price_field
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iStochastic indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iS
1704
Technical Indicators
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the StochasticBuffer array is greater than the number of values in the iStochastic i
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iStochastic indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(StochasticBuffer,SignalBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Stochastic Oscillator indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iStochastic indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &main_buffer[],
double &signal_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the StochasticBuffer array with values from the indicator buffer that has 0 in
if(CopyBuffer(ind_handle,MAIN_LINE,0,amount,main_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iStochastic indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the SignalBuffer array with values from the indicator buffer that has index 1
1705
Technical Indicators
if(CopyBuffer(ind_handle,SIGNAL_LINE,0,amount,signal_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iStochastic indicator, error code %d",GetLastError(
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1706
Technical Indicators
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,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iTEMA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1707
Technical Indicators
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All the other parameters are similar to the standard Triple Exponential Movi
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iTEMA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iTEMA,
// use iTEMA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iTEMA;
input int
ma_period=14;
// period of averaging
input int
ma_shift=0;
// shift
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iTEMABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iTEMABuffer,INDICATOR_DATA);
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
1708
Technical Indicators
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iTEMA)
handle=iTEMA(name,period,ma_period,ma_shift,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[3];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- shift
pars[1].type=TYPE_INT;
pars[1].integer_value=ma_shift;
//--- type of price
pars[2].type=TYPE_INT;
pars[2].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_TEMA,3,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iTEMA indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Triple Exponential Moving Average indicator is calculated for
short_name=StringFormat("iTEMA(%s/%s, %d, %d, %s)",name,EnumToString(period),
ma_period,ma_shift,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
1709
Technical Indicators
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[])
{
//--- number of values copied from the iTEMA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iT
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iTEMABuffer array is greater than the number of values in the iTEMA indicator fo
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values from the Triple Exponential Moving Average indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iTEMABuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Triple Exponential Moving Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
1710
Technical Indicators
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iTEMA indicator
//+------------------------------------------------------------------+
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iTEMABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-t_shift,amount,tema_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iTEMA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1711
Technical Indicators
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
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iTriX.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
1712
Technical Indicators
#property indicator_buffers 1
#property indicator_plots
"iTriX"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrRed
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iTriX,
// use iTriX
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iTriX;
input int
ma_period=14;
// period
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iTriXBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iTriXBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
1713
Technical Indicators
}
//--- create handle of the indicator
if(type==Call_iTriX)
handle=iTriX(name,period,ma_period,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[2];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=ma_period;
//--- type of price
pars[1].type=TYPE_INT;
pars[1].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_TRIX,2,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iTriX indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Triple Exponential Moving Averages Oscillator is calculated for
short_name=StringFormat("iTriX(%s/%s, %d, %s)",name,EnumToString(period),
ma_period,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iTriX indicator
1714
Technical Indicators
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iT
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iTriXBuffer array is greater than the number of values in the iTriX indicator fo
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values from the Triple Exponential Moving Averages Oscillator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iTriXBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Triple Exponential Moving Averages Oscillator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iTriX indicator
//+------------------------------------------------------------------+
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iTriXBuffer array with values from the indicator buffer that has 0 index
1715
Technical Indicators
if(CopyBuffer(ind_handle,0,0,amount,trix_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iTriX indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1716
Technical Indicators
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
// averaging period
calc_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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iWPR.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots
"iWPR"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrCyan
1717
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
-20.0
#property indicator_level2
-80.0
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iWPR,
// use iWPR
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iWPR;
input int
calc_period=14;
// period
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iWPRBuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iWPRBuffer,INDICATOR_DATA);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
1718
Technical Indicators
//--- create handle of the indicator
if(type==Call_iWPR)
handle=iWPR(name,period,calc_period);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
//--- period
pars[0].type=TYPE_INT;
pars[0].integer_value=calc_period;
handle=IndicatorCreate(name,period,IND_WPR,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iWPR indicator for the symbol %s/%s, error code %
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Williams' Percent Range indicator is calculated for
short_name=StringFormat("iWPR(%s/%s, %d)",name,EnumToString(period),calc_period);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iWPR indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
1719
Technical Indicators
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iW
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iWPRBuffer array is greater than the number of values in the iWPR indicator for
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values of the Williams' Percent Range indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iWPRBuffer,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Larry Williams' Percent Range indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iWPR indicator
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &wpr_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iWPRBuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,0,amount,wpr_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iWPR indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
1720
Technical Indicators
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1721
Technical Indicators
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,
int
ema_period,
int
ma_shift,
ENUM_APPLIED_PRICE applied_price
);
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iVIDyA.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
1722
Technical Indicators
#property description "The indicator demonstrates how to obtain data"
#property description "of indicator buffers for the iVIDyA technical indicator."
#property description "A symbol and timeframe used for calculation of the indicator,"
#property description "are set by the symbol and period parameters."
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property description "All other parameters like in the standard Variable Index Dynamic Average."
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots
"iVIDyA"
#property indicator_type1
DRAW_LINE
#property indicator_color1
clrBlue
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iVIDyA,
// use iVIDyA
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iVIDyA;
input int
cmo_period=15;
input int
ema_period=12;
input int
ma_shift=0;
// shift
input ENUM_APPLIED_PRICE
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iVIDyABuffer[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iVIDyABuffer,INDICATOR_DATA);
1723
Technical Indicators
//--- set shift
PlotIndexSetInteger(0,PLOT_SHIFT,ma_shift);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iVIDyA)
handle=iVIDyA(name,period,cmo_period,ema_period,ma_shift,applied_price);
else
{
//--- fill the structure with parameters of the indicator
MqlParam pars[4];
//--- the Chande Momentum period
pars[0].type=TYPE_INT;
pars[0].integer_value=cmo_period;
//--- period of the factor of smoothing
pars[1].type=TYPE_INT;
pars[1].integer_value=ema_period;
//--- shift
pars[2].type=TYPE_INT;
pars[2].integer_value=ma_shift;
//--- type of price
pars[3].type=TYPE_INT;
pars[3].integer_value=applied_price;
handle=IndicatorCreate(name,period,IND_VIDYA,4,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iVIDyA indicator for the symbol %s/%s, error code
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Variable Index Dynamic Average indicator is calculated for
short_name=StringFormat("iVIDyA(%s/%s, %d, %d, %d, %s)",name,EnumToString(period),
cmo_period,ema_period,ma_shift,EnumToString(applied_price));
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
1724
Technical Indicators
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iVIDyA indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iV
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iVIDyABuffer array is greater than the number of values in the iVIDyA indicator
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the array with values from the Variable Index Dynamic Average indicator
//--- if FillArrayFromBuffer returns false, it means the information is nor ready yet, quit operati
if(!FillArrayFromBuffer(iVIDyABuffer,ma_shift,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
1725
Technical Indicators
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Variable Index Dynamic Average indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iVIDyA indicator
//+------------------------------------------------------------------+
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iVIDyABuffer array with values from the indicator buffer that has 0 index
if(CopyBuffer(ind_handle,0,-v_shift,amount,vidya_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iVIDyA indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1726
Technical Indicators
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
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.
Return 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.
Example:
//+------------------------------------------------------------------+
//|
Demo_iVolumes.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
#property version
"1.00"
#property description "The method of creation of the handle is set through the 'type' parameter (fu
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots
"iVolumes"
#property indicator_type1
DRAW_COLOR_HISTOGRAM
#property indicator_color1
clrGreen, clrRed
1727
Technical Indicators
#property indicator_style1
STYLE_SOLID
#property indicator_width1
//+------------------------------------------------------------------+
//| Enumeration of the methods of handle creation
//+------------------------------------------------------------------+
enum Creation
{
Call_iVolumes,
// use iVolumes
Call_IndicatorCreate
// use IndicatorCreate
};
//--- input parameters
input Creation
type=Call_iVolumes;
input ENUM_APPLIED_VOLUME
applied_volume=VOLUME_TICK;
// type of volume
input string
symbol=" ";
// symbol
input ENUM_TIMEFRAMES
period=PERIOD_CURRENT;
// timeframe
iVolumesBuffer[];
double
iVolumesColors[];
handle;
bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- assignment of array to indicator buffer
SetIndexBuffer(0,iVolumesBuffer,INDICATOR_DATA);
SetIndexBuffer(1,iVolumesColors,INDICATOR_COLOR_INDEX);
//--- determine the symbol the indicator is drawn for
name=symbol;
//--- delete spaces to the right and to the left
StringTrimRight(name);
StringTrimLeft(name);
//--- if it results in zero length of the 'name' string
if(StringLen(name)==0)
{
//--- take the symbol of the chart the indicator is attached to
name=_Symbol;
}
//--- create handle of the indicator
if(type==Call_iVolumes)
handle=iVolumes(name,period,applied_volume);
else
1728
Technical Indicators
{
//--- fill the structure with parameters of the indicator
MqlParam pars[1];
//--- type of price
pars[0].type=TYPE_INT;
pars[0].integer_value=applied_volume;
handle=IndicatorCreate(name,period,IND_VOLUMES,1,pars);
}
//--- if the handle is not created
if(handle==INVALID_HANDLE)
{
//--- tell about the failure and output the error code
PrintFormat("Failed to create handle of the iVolumes indicator for the symbol %s/%s, error co
name,
EnumToString(period),
GetLastError());
//--- the indicator is stopped early
return(INIT_FAILED);
}
//--- show the symbol/timeframe the Volumes indicator is calculated for
short_name=StringFormat("iVolumes(%s/%s, %s)",name,EnumToString(period),EnumToString(applied_vol
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- normal initialization of the indicator
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- number of values copied from the iVolumes indicator
int values_to_copy;
//--- determine the number of values calculated in the indicator
int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());
return(0);
}
//--- if it is the first start of calculation of the indicator or if the number of values in the iV
1729
Technical Indicators
//---or if it is necessary to calculated the indicator for two or more bars (it means something has
if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- if the iVolumesBuffer array is greater than the number of values in the iVolumes indica
//--- otherwise, we copy less than the size of indicator buffers
if(calculated>rates_total) values_to_copy=rates_total;
else
values_to_copy=calculated;
}
else
{
//--- it means that it's not the first time of the indicator calculation, and since the last
//--- for calculation not more than one bar is added
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- fill the arrays with values of the iVolumes indicator
//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operat
if(!FillArraysFromBuffers(iVolumesBuffer,iVolumesColors,handle,values_to_copy)) return(0);
//--- form the message
string comm=StringFormat("%s ==>
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
short_name,
values_to_copy);
//--- display the service message on the chart
Comment(comm);
//--- memorize the number of values in the Volumes indicator
bars_calculated=calculated;
//--- return the prev_calculated value for the next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iVolumes indicator
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &volume_buffer[],
double &color_buffer[],
int ind_handle,
int amount
)
{
//--- reset error code
ResetLastError();
//--- fill a part of the iVolumesBuffer array with values from the indicator buffer that has 0 inde
if(CopyBuffer(ind_handle,0,0,amount,volume_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iVolumes indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- fill a part of the iVolumesColors array with values from the indicator buffer that has index
1730
Technical Indicators
if(CopyBuffer(ind_handle,1,0,amount,color_buffer)<0)
{
//--- if the copying fails, tell the error code
PrintFormat("Failed to copy data from the iVolumes indicator, error code %d",GetLastError());
//--- quit with zero result - it means that the indicator is considered as not calculated
return(false);
}
//--- everything is fine
return(true);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear the chart after deleting the indicator
Comment("");
}
1731
Action
FrameFirst
FrameFilter
FrameNext
FrameInputs
FrameAdd
ParameterGetRange
ParameterSetRange
See also
Testing Statistics, Properties of a Running MQL5 Program
1732
FrameFirst
Moves a pointer of frame reading to the beginning and resets a set filter.
bool FrameFirst();
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
1733
FrameFilter
Sets the frame reading filter and moves the pointer to the beginning.
bool FrameFilter(
const string
name,
// Public name/label
long
id
// Public ID
);
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Note
If an empty string is passed as the first parameter, the filter will work only with a numeric
parameter, i.e. only frames with the specified id will be viewed. If the value of the second
parameter is ULONG_MAX, only a text filter works.
Call of FrameFilter("", ULONG_MAX) is equivalent to calling FrameFirst(), i.e. equal to not using any
filter.
1734
FrameNext
Reads a frame and moves the pointer to the next one. There are two variants of the function.
1. Calling to receive one numeric value
bool FrameNext(
ulong&
pass,
// The number of a pass in the optimization, during which the frame has been
string& name,
// Public name/label
long&
// Public ID
id,
double& value
// Value
);
pass,
// The number of a pass in the optimization, during which the frame has been
string& name,
// Public name/label
long&
// Public ID
id,
double& value,
// Value
void&
data[]
);
Parameters
pass
[out] The number of a pass during optimization in the strategy tester.
name
[out] The name of the identifier.
id
[out] The value of the identifier.
value
[out] A single numeric value.
data
[out] An array of any type.
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Note
In the second version of the call, you must correctly handle the received data in the data[] array.
1735
FrameInputs
Receives input parameters, on which the frame with the specified pass number is formed.
bool FrameInputs(
ulong
pass,
string& parameters[],
uint&
parameters_count
);
Parameters
pass
[out] The number of a pass during optimization in the strategy tester.
parameters
[out] A string array with the description of names and parameter values
parameters_count
[out] The number of elements in the array parameters[].
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Note
Having obtained the number of strings parameters_count in the parameters[] array, you can
organize a loop to go through all records. This will help you find the values of input parameters of an
Expert Advisor for the specified pass number.
1736
FrameAdd
Adds a frame with data. There are two variants of the function.
1. Adding data from a file
bool FrameAdd(
const string name,
// Public name/label
long
id,
// Public ID
double
value,
// Value
const string
filename
);
// Public name/label
long
id,
// Public ID
double
value,
// Value
const void&
data[]
);
Parameters
name
[in] Public frame label. It can be used for a filter in the FrameFilter() function.
id
[in] A public identifier of the frame. It can be used for a filter in the FrameFilter() function.
value
[in] A numeric value to write into the frame. It is used to transmit a single pass result like in the
OnTester() function.
filename
[in] The name of the file that contains data to add to the frame. The file must be locate in the
folder MQL5/Files.
data
[in] An array of any type to write into the frame. Passed by reference.
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
1737
ParameterGetRange
Receives data on the values range and the change step for an input variable when optimizing an
Expert Advisor in the Strategy Tester. There are 2 variants of the function.
1. Receiving data for the integer type input parameter
bool ParameterGetRange(
const string name,
bool&
enable,
long&
value,
// parameter value
long&
start,
// initial value
long&
step,
// change step
long&
stop
// final value
);
double&
enable,
double&
value,
// parameter value
double&
start,
// initial value
double&
step,
// change step
double&
stop
// final value
);
Parameters
name
[in] input variable ID. These variables are external parameters of an application. Their values can
be specified when launching on a chart or during a single test.
enable
[out] Flag that this parameter can be used to enumerate the values during the optimization in the
Strategy Tester.
value
[out] Parameter value.
start
[out] Initial parameter value during the optimization.
step
[out] Parameter change step when enumerating its values.
stop
[out] Final parameter value during the optimization.
Return Value
Returns true if successful, otherwise false. For information about the error, use the GetLastError()
1738
Input1=1;
input double
Input2=2.0;
input bool
Input3=false;
input ENUM_DAY_OF_WEEK
Input4=SUNDAY;
//+------------------------------------------------------------------+
//| Expert initialization function
//+------------------------------------------------------------------+
int OnInit()
{
//--- Expert Advisor is designed for operation only in the Strategy Tester
if(!MQL5InfoInteger(MQL5_OPTIMIZATION))
{
MessageBox("Should be launched in the optimization mode of the Strategy Tester!");
//--- finish the Expert Advisor operation in advance and remove from the chart
return(INIT_FAILED);
}
//--- successful completion of initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| TesterInit function
//+------------------------------------------------------------------+
void OnTesterInit()
{
//--- example for long type input parameter
string name="Input1";
bool enable;
long par1,par1_start,par1_step,par1_stop;
ParameterGetRange(name,enable,par1,par1_start,par1_step,par1_stop);
Print("First parameter");
1739
enable=%s
name,par1,(string)enable,par1_start,par1_stop,par1_step);
//--- example for double type input parameter
name="Input2";
double par2,par2_start,par2_step,par2_stop;
ParameterGetRange(name,enable,par2,par2_start,par2_step,par2_stop);
Print("Second parameter");
PrintFormat("%s=%G
enable=%s
name,par2,(string)enable,par2_start,par2_stop,par2_step);
//--- example for bool type input parameter
name="Input3";
long par3,par3_start,par3_step,par3_stop;
ParameterGetRange(name,enable,par3,par3_start,par3_step,par3_stop);
Print("Third parameter");
PrintFormat("%s=%s
enable=%s
from %s to %s",
name,(string)par3,(string)enable,
(string)par3_start,(string)par3_stop);
//--- example for enumeration type input parameter
name="Input4";
long par4,par4_start,par4_step,par4_stop;
ParameterGetRange(name,enable,par4,par4_start,par4_step,par4_stop);
Print("Fourth parameter");
PrintFormat("%s=%s
enable=%s
from %s to %s",
name,EnumToString((ENUM_DAY_OF_WEEK)par4),(string)enable,
EnumToString((ENUM_DAY_OF_WEEK)par4_start),
EnumToString((ENUM_DAY_OF_WEEK)par4_stop));
}
//+------------------------------------------------------------------+
//| TesterDeinit function
//+------------------------------------------------------------------+
void OnTesterDeinit()
{
//--- this message will be shown after optimization is complete
Print(__FUNCTION__," Optimization completed");
}
1740
ParameterSetRange
Specifies the use of input variable when optimizing an Expert Advisor in the Strategy Tester: value,
change step, initial and final values. There are 2 variants of the function.
1. Specifying the values for the integer type input parameter
bool ParameterSetRange(
const string name,
bool
enable,
long
value,
// parameter value
long
start,
// initial value
long
step,
// change step
long
stop
// final value
);
double
enable,
double
value,
// parameter value
double
start,
// initial value
double
step,
// change step
double
stop
// final value
);
Parameters
name
[in] input or sinput variable ID. These variables are external parameters of an application. Their
values can be specified when launching the program.
enable
[in] Enable this parameter to enumerate the values during the optimization in the Strategy
Tester.
value
[in] Parameter value.
start
[in] Initial parameter value during the optimization.
step
[in] Parameter change step when enumerating its values.
stop
[in] Final parameter value during the optimization.
Return Value
Returns true if successful, otherwise false. For information about the error, use the GetLastError()
1741
1742
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
EventSetMillisecondTimer
EventSetTimer
EventKillTimer
EventChartCustom
See also
Types of Chart Events
1743
EventSetMillisecondTimer
The function indicates to the client terminal that timer events should be generated at intervals less
than one second for this Expert Advisor or indicator.
bool EventSetMillisecondTimer(
int milliseconds
// number of milliseconds
);
Parameters
milliseconds
[in] Number of milliseconds defining the frequency of timer events.
Return Value
In case of successful execution, returns true, otherwise - false. To receive an error code,
GetLastError() function should be called.
Note
This feature is designed for the cases when high-resolution timer is required. In other words, timer
events should be received more frequently than once per second. If a conventional timer with the
period of more than one second is enough for you, use EventSetTimer().
The minimum interval of 1000 milliseconds is used in the strategy tester. In general, when the timer
period is reduced, the testing time is increased, as the handler of timer events is called more often.
When working in real-time mode, timer events are generated no more than 1 time in 10-16
milliseconds due to hardware limitations.
Usually, this function should be called from OnInit() function or in class constructor. To handle
events coming from the timer, an Expert Advisor or an indicator should have OnTimer() function.
Each Expert Advisor and each indicator work with its own timer receiving events solely from this
timer. During mql5 application shutdown, the timer is forcibly destroyed in case it has been created
but has not been disabled by EventKillTimer() function.
Only one timer can be launched for each program. Each mql5 application and chart have their own
queue of events where all newly arrived events are placed. If the queue already contains Timer
event or this event is in the processing stage, then the new Timer event is not added to mql5
application queue.
1744
EventSetTimer
The function indicates to the client terminal, that for this indicator or Expert Advisor, events from
the timer must be generated with the specified periodicity.
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.
For each program no more than one timer can be run. Each mql5 program and each chart has its own
queue of events, in which all the newly received events are placed. If the Timer event is present in
the queue or is being processed, the new Timer event will not be placed in the queue of the mql5
program.
1745
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
1746
EventChartCustom
The function generates a custom event for the specified chart.
bool EventChartCustom(
long
chart_id,
ushort custom_event_id,
// event identifier
long
lparam,
double dparam,
string sparam
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
custom_event_id
[in] ID of the user events. This identifier is automatically
CHARTEVENT_CUSTOM and converted to the integer type.
added
to
the
value
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
Returns true if a custom event has been successfully placed in the events queue of the chart that
receives the events. 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.
Event
Event
of
keystroke
Value of the id
parameter
Value of
lparam
parameter
the
CHARTEVENT_KE
YDOWN
code
of
pressed key
Value of
dparam
parameter
the
Repeat
count
(the number of
times
the
keystroke
is
Value of
sparam
parameter
the
1747
repeated as a
result of the user
holding down the
key)
keyboard buttons
CHARTEVENT_MO
USE_MOVE
the X coordinate
the Y coordinate
Event
of
graphical object
creation
(if
CHART_EVENT_O
BJECT_CREATE=t
rue is set for the
chart)
CHARTEVENT_OB
JECT_CREATE
Name of the
created graphical
object
Event of change
of an object
property via the
properties dialog
CHARTEVENT_OB
JECT_CHANGE
Name of the
modified
graphical object
Event
of
graphical object
deletion
(if
CHART_EVENT_O
BJECT_DELETE=t
rue is set for the
chart)
CHARTEVENT_OB
JECT_DELETE
Name of the
deleted graphical
object
Event
of
a
mouse click on
the chart
CHARTEVENT_C
LICK
the X coordinate
the Y coordinate
Event
of
a
mouse click in a
graphical object
belonging to the
chart
CHARTEVENT_OB
JECT_CLICK
the X coordinate
the Y coordinate
Name of the
graphical object,
on which the
event occurred
Event
of
a
graphical object
dragging using
the mouse
CHARTEVENT_OB
JECT_DRAG
Name of the
moved graphical
object
Event of the
finished
text
editing in the
entry box of the
LabelEdit
graphical object
CHARTEVENT_OB
JECT_ENDEDIT
Name of the
LabelEdit
graphical object,
in which text
editing
has
completed
1748
Event of changes
on a chart
CHARTEVENT_C
HART_CHANGE
ID of the user
event under the
N number
CHARTEVENT_CU
STOM+N
Example:
//+------------------------------------------------------------------+
//|
ButtonClickExpert.mq5 |
//|
//|
https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link
"https://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);
//--- Create a label for displaying information
ObjectCreate(0,labelID,OBJ_LABEL,0,100,100);
ObjectSetInteger(0,labelID,OBJPROP_COLOR,clrRed);
ObjectSetInteger(0,labelID,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,labelID,OBJPROP_YDISTANCE,50);
ObjectSetString(0,labelID,OBJPROP_FONT,"Trebuchet MS");
ObjectSetString(0,labelID,OBJPROP_TEXT,"No information");
ObjectSetInteger(0,labelID,OBJPROP_FONTSIZE,20);
ObjectSetInteger(0,labelID,OBJPROP_SELECTABLE,0);
1749
//+------------------------------------------------------------------+
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;
1750
//+------------------------------------------------------------------+
void BroadcastEvent(long lparam,double dparam,string sparam)
{
int eventID=broadcastEventID-CHARTEVENT_CUSTOM;
long currChart=ChartFirst();
int i=0;
while(i<CHARTS_MAX)
{
EventChartCustom(currChart,eventID,lparam,dparam,sparam);
currChart=ChartNext(currChart); // We have received a new chart from the previous
if(currChart==-1) break;
1751
See also
Events of the client terminal, Event handler functions
1752
Action
CLHandleType
CLGetInfoInteger
CLContextCreate
CLContextFree
CLGetDeviceInfo
CLProgramCreate
CLProgramFree
CLKernelCreate
CLKernelFree
CLSetKernelArg
CLSetKernelArgMem
CLBufferCreate
CLBufferFree
CLBufferWrite
CLBufferRead
CLExecute
1753
CLHandleType
Returns the type of an OpenCL handle as a value of the ENUM_OPENCL_HANDLE_TYPE enumeration.
ENUM_OPENCL_HANDLE_TYPE CLHandleType(
int handle
);
Parameters
handle
[in] A handle to an OpenCL object: a context, a kernel or an OpenCL program.
Return Value
The type of the OpenCL handle as a value of the ENUM_OPENCL_HANDLE_TYPE enumeration.
ENUM_OPENCL_HANDLE_TYPE
Identifier
Description
OPENCL_INVALID
Incorrect handle
OPENCL_CONTEXT
OPENCL_PROGRAM
OPENCL_KERNEL
OPENCL_BUFFER
1754
CLGetInfoInteger
Returns the value of an integer property for an OpenCL object or device.
long CLGetInfoInteger(
int handle,
ENUM_OPENCL_PROPERTY_INTEGER prop
// Requested property
);
Parameters
handle
[in] A handle to the OpenCL object or number of the OpenCL device. Numbering of OpenCL
devices starts with zero.
prop
[in] The type of a requested property from the ENUM_OPENCL_PROPERTY_INTEGER enumeration,
the value of which you want to obtain.
Return Value
The value of the property if successful or -1 in case of an error. For information about the error, use
the GetLastError() function.
ENUM_OPENCL_PROPERTY_INTEGER
Identifier
Description
Type
CL_DEVICE_COUNT
int
CL_DEVICE_TYPE
Type of device
ENUM_CL_DEVICE_TYPE
CL_DEVICE_VENDOR_ID
uint
CL_DEVICE_MAX_COMPUTE_UN
ITS
uint
CL_DEVICE_MAX_CLOCK_FREQ
UENCY
uint
CL_DEVICE_GLOBAL_MEM_SIZ
E
ulong
CL_DEVICE_LOCAL_MEM_SIZE
uint
CL_BUFFER_SIZE
ulong
1755
The ENUM_CL_DEVICE_TYPE enumeration contains possible types of devices supporting OpenCL. You
can receive the type of device by its number or the handle of the OpenCL object by calling
CLGetInfoInteger(handle_or_deviceN, CL_DEVICE_TYPE).
ENUM_CL_DEVICE_TYPE
Identifier
Description
CL_DEVICE_ACCELERATOR
CL_DEVICE_CPU
CL_DEVICE_GPU
CL_DEVICE_DEFAULT
CL_DEVICE_CUSTOM
Example:
void OnStart()
{
int cl_ctx;
//--- initialize OpenCL context
if((cl_ctx=CLContextCreate(CL_USE_GPU_ONLY))==INVALID_HANDLE)
{
Print("OpenCL not found");
return;
}
//--- Display general information about OpenCL device
1756
CLGetInfoString
Returns string value of a property for OpenCL object or device.
bool CLGetInfoString(
int handle,
ENUM_OPENCL_PROPERTY_STRING
prop,
// requested property
string& value
// referenced string
);
Parameters
handle
[in] OpenCL object handle or OpenCL device number. The numbering of OpenCL devices starts
with zero.
prop
[in] Type of requested property from ENUM_OPENCL_PROPERTY_STRING enumeration, the value
of which should be obtained.
value
[out] String for receiving the property value.
Return Value
true if successful, otherwise false. For information about the error, use the GetLastError() function.
ENUM_OPENCL_PROPERTY_STRING
Identifier
CL_PLATFORM_PROFILE
Description
CL_PLATFORM_PROFILE - OpenCL Profile. Profile
name may be one of the following values:
FULL_PROFILE - implementation supports
implementation
supports OpenCL as a supplement. Amended
profile is defined as a subset for each
OpenCL version.
CL_PLATFORM_VERSION
OpenCL version
CL_PLATFORM_VENDOR
CL_PLATFORM_EXTENSIONS
CL_DEVICE_NAME
Device name
CL_DEVICE_VENDOR
Vendor name
CL_DRIVER_VERSION
OpenCL
driver
version
in
1757
implementation
supports OpenCL as a supplement. Amended
profile is defined as a subset for each
OpenCL version.
CL_DEVICE_VERSION
OpenCL
version
in
"OpenCL<space><major_version.minor_version><s
pace><vendor-specific information>" format
CL_DEVICE_EXTENSIONS
CL_DEVICE_BUILT_IN_KERNELS
CL_DEVICE_OPENCL_C_VERSION
Example:
void OnStart()
{
int cl_ctx;
string str;
//--- initialize OpenCL context
if((cl_ctx=CLContextCreate(CL_USE_GPU_ONLY))==INVALID_HANDLE)
{
Print("OpenCL not found");
return;
}
//--- Display information about the platform
if(CLGetInfoString(cl_ctx,CL_PLATFORM_NAME,str))
Print("OpenCL platform name: ",str);
if(CLGetInfoString(cl_ctx,CL_PLATFORM_VENDOR,str))
1758
1759
CLContextCreate
Creates an OpenCL context and returns its handle.
int CLContextCreate(
int device
);
Parameter
device
[in] The ordinal number of the OpenCL-device in the system. Instead of a specific number, you
can specify one of the following values:
CL_USE_ANY any available device with OpenCL support is allowed;
CL_USE_CPU_ONLY only OpenCL emulation on CPU is allowed;
CL_USE_GPU_ONLY OpenCL emulation is prohibited and only specialized devices with OpenCL
1760
CLContextFree
Removes an OpenCL context.
void CLContextFree(
int context
);
Parameters
context
[in] Handle of the OpenCL context.
Return Value
None. In the case of an internal error the value of _LastError changes. For information about the
error, use the GetLastError() function.
1761
CLGetDeviceInfo
The function receives device property from OpenCL driver.
bool CLGetDeviceInfo(
int
handle,
int
property_id,
// requested property ID
uchar&
data[],
uint&
size
);
Parameters
handle
[in] OpenCL device index or OpenCL handle created by CLContextCreate() function.
property_id
[in] ID of the OpenCL device property that should be received. The values can be of one of the
predetermined ones listed in the table below.
data[]
[out] The array for receiving data on the requested property.
size
[out] Size of the received data in the array data[].
Return Value
true if successful, otherwise false. For information about the error, use the GetLastError() function.
Note
For one-dimensional arrays, the number of the element, from which data reading for OpenCL buffer
starts, is calculated considering AS_SERIES flag.
The list of available IDs of OpenCL device properties
Exact description of the property and its functions can be found at the official OpenCL web site.
Identifier
Value
CL_DEVICE_TYPE
0x1000
CL_DEVICE_VENDOR_ID
0x1001
CL_DEVICE_MAX_COMPUTE_UNITS
0x1002
CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
0x1003
CL_DEVICE_MAX_WORK_GROUP_SIZE
0x1004
CL_DEVICE_MAX_WORK_ITEM_SIZES
0x1005
CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHA
R
0x1006
1762
CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHO
RT
0x1007
CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT
0x1008
CL_DEVICE_PREFERRED_VECTOR_WIDTH_LON
G
0x1009
CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLO
AT
0x100A
CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOU
BLE
0x100B
CL_DEVICE_MAX_CLOCK_FREQUENCY
0x100C
CL_DEVICE_ADDRESS_BITS
0x100D
CL_DEVICE_MAX_READ_IMAGE_ARGS
0x100E
CL_DEVICE_MAX_WRITE_IMAGE_ARGS
0x100F
CL_DEVICE_MAX_MEM_ALLOC_SIZE
0x1010
CL_DEVICE_IMAGE2D_MAX_WIDTH
0x1011
CL_DEVICE_IMAGE2D_MAX_HEIGHT
0x1012
CL_DEVICE_IMAGE3D_MAX_WIDTH
0x1013
CL_DEVICE_IMAGE3D_MAX_HEIGHT
0x1014
CL_DEVICE_IMAGE3D_MAX_DEPTH
0x1015
CL_DEVICE_IMAGE_SUPPORT
0x1016
CL_DEVICE_MAX_PARAMETER_SIZE
0x1017
CL_DEVICE_MAX_SAMPLERS
0x1018
CL_DEVICE_MEM_BASE_ADDR_ALIGN
0x1019
CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE
0x101A
CL_DEVICE_SINGLE_FP_CONFIG
0x101B
CL_DEVICE_GLOBAL_MEM_CACHE_TYPE
0x101C
CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE
0x101D
CL_DEVICE_GLOBAL_MEM_CACHE_SIZE
0x101E
CL_DEVICE_GLOBAL_MEM_SIZE
0x101F
CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
0x1020
CL_DEVICE_MAX_CONSTANT_ARGS
0x1021
CL_DEVICE_LOCAL_MEM_TYPE
0x1022
CL_DEVICE_LOCAL_MEM_SIZE
0x1023
CL_DEVICE_ERROR_CORRECTION_SUPPORT
0x1024
1763
CL_DEVICE_PROFILING_TIMER_RESOLUTION
0x1025
CL_DEVICE_ENDIAN_LITTLE
0x1026
CL_DEVICE_AVAILABLE
0x1027
CL_DEVICE_COMPILER_AVAILABLE
0x1028
CL_DEVICE_EXECUTION_CAPABILITIES
0x1029
CL_DEVICE_QUEUE_PROPERTIES
0x102A
CL_DEVICE_NAME
0x102B
CL_DEVICE_VENDOR
0x102C
CL_DRIVER_VERSION
0x102D
CL_DEVICE_PROFILE
0x102E
CL_DEVICE_VERSION
0x102F
CL_DEVICE_EXTENSIONS
0x1030
CL_DEVICE_PLATFORM
0x1031
CL_DEVICE_DOUBLE_FP_CONFIG
0x1032
CL_DEVICE_PREFERRED_VECTOR_WIDTH_HAL
F
0x1034
CL_DEVICE_HOST_UNIFIED_MEMORY
0x1035
CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR
0x1036
CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT
0x1037
CL_DEVICE_NATIVE_VECTOR_WIDTH_INT
0x1038
CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG
0x1039
CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT
0x103A
CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE
0x103B
CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF
0x103C
CL_DEVICE_OPENCL_C_VERSION
0x103D
CL_DEVICE_LINKER_AVAILABLE
0x103E
CL_DEVICE_BUILT_IN_KERNELS
0x103F
CL_DEVICE_IMAGE_MAX_BUFFER_SIZE
0x1040
CL_DEVICE_IMAGE_MAX_ARRAY_SIZE
0x1041
CL_DEVICE_PARENT_DEVICE
0x1042
CL_DEVICE_PARTITION_MAX_SUB_DEVICES
0x1043
CL_DEVICE_PARTITION_PROPERTIES
0x1044
CL_DEVICE_PARTITION_AFFINITY_DOMAIN
0x1045
1764
CL_DEVICE_PARTITION_TYPE
0x1046
CL_DEVICE_REFERENCE_COUNT
0x1047
CL_DEVICE_PREFERRED_INTEROP_USER_SYNC
0x1048
CL_DEVICE_PRINTF_BUFFER_SIZE
0x1049
CL_DEVICE_IMAGE_PITCH_ALIGNMENT
0x104A
CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMEN
T
0x104B
Example:
void OnStart()
{
//--int dCount= CLGetInfoInteger(0,CL_DEVICE_COUNT);
for(int i = 0; i<dCount; i++)
{
int clCtx=CLContextCreate(i);
if(clCtx == -1)
Print("ERROR in CLContextCreate");
string device;
CLGetInfoString(clCtx,CL_DEVICE_NAME,device);
Print(i,": ",device);
uchar data[1024];
uint size;
CLGetDeviceInfo(clCtx,CL_DEVICE_VENDOR,data,size);
Print("size = ",size);
string str=CharArrayToString(data);
Print(str);
}
}
//--- example of entries in Experts journal
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
size = 32
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
Tahiti
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
Intel(R) Corporation
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
size = 21
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
1:
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
NVIDIA Corporation
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
size = 19
//
2013.07.24 10:50:48
opencl (EURUSD,H1)
1765
CLProgramCreate
Creates an OpenCL program from a source code.
int CLProgramCreate(
int
context,
);
An overloaded function version creates an OpenCL program and writes compiler messages into the
passed string.
int CLProgramCreate(
int
context,
// Source code
string
&build_log
);
Parameters
context
[in] Handle of the OpenCL context.
source
[in] String with the source code of the OpenCL program.
&build_log
[in] A string for receiving the OpenCL compiler messages.
Return Value
A handle to an OpenCL object if successful. In case of error -1 is returned. For information about
the error, use the GetLastError() function.
Note
At the moment, the following error codes are used:
ERR_OPENCL_INVALID_HANDLE invalid handle to the context OpenCL.
ERR_INVALID_PARAMETER invalid string parameter.
ERR_NOT_ENOUGH_MEMORY not enough memory to complete operation.
ERR_OPENCL_PROGRAM_CREATE internal error of OpenCL or compilation error.
In some graphic cards working with the double type numbers is disabled by default. This can lead to
compilation error 5105. To enable support for the double type numbers, please add the following
directive to your OpenCL program: #pragma OPENCL EXTENSION cl_khr_fp64 : enable. However if a
graphic card doesn't support double, enabling this directive won't be of help.
Example:
//+------------------------------------------------------------------+
//| OpenCL kernel
//+------------------------------------------------------------------+
const string
1766
\r\n"
\r\n"
"
"
"
const
int N,
\r\n"
const
int total_arrays)
\r\n"
\r\n"
"
uint kernel_index=get_global_id(0);
\r\n"
"
if (kernel_index>total_arrays) return;
\r\n"
"
uint local_start_offset=kernel_index*N;
\r\n"
"
\r\n"
"
"
data[i+local_start_offset] *= 2.0;
"
"
\r\n"
\r\n"
\r\n"
\r\n";
//+------------------------------------------------------------------+
//| Test_CPU
//+------------------------------------------------------------------+
bool Test_CPU(double &data[],const int N,const int id,const int total_arrays)
{
//--- check array size
if(ArraySize(data)==0) return(false);
//--- check array index
if(id>total_arrays) return(false);
//--- calculate local offset for array with index id
int local_start_offset=id*N;
//--- multiply elements by 2
for(int i=0; i<N; i++)
{
data[i+local_start_offset]*=2.0;
}
return true;
}
//--#define ARRAY_SIZE
100
#define TOTAL_ARRAYS 5
int cl_prg;
int cl_krn;
int cl_mem;
//+------------------------------------------------------------------+
1767
if((cl_mem=CLBufferCreate(cl_ctx,ARRAY_SIZE*TOTAL_ARRAYS*sizeof(double),CL_MEM_READ_WRITE))==INV
{
CLKernelFree(cl_krn);
CLProgramFree(cl_prg);
CLContextFree(cl_ctx);
Print("OpenCL buffer create failed. Error=",GetLastError());
return(1);
}
//--- set OpenCL kernel constant parameters
CLSetKernelArgMem(cl_krn,0,cl_mem);
CLSetKernelArg(cl_krn,1,ARRAY_SIZE);
CLSetKernelArg(cl_krn,2,TOTAL_ARRAYS);
//--- prepare data arrays
ArrayResize(DataArray1,ARRAY_SIZE*TOTAL_ARRAYS);
ArrayResize(DataArray2,ARRAY_SIZE*TOTAL_ARRAYS);
//--- fill arrays with data
for(int j=0; j<TOTAL_ARRAYS; j++)
{
//--- calculate local start offset for jth array
uint local_offset=j*ARRAY_SIZE;
//--- prepare array with index j
for(int i=0; i<ARRAY_SIZE; i++)
{
//--- fill arrays with function MathCos(i+j);
1768
offset[]={0};
work[]={TOTAL_ARRAYS};
}
}
PrintFormat("Total error: %f",total_error);
//--- delete OpenCL objects
//--- free OpenCL buffer
CLBufferFree(cl_mem);
//--- free OpenCL kernel
CLKernelFree(cl_krn);
//--- free OpenCL program
CLProgramFree(cl_prg);
//--- free OpenCL context
CLContextFree(cl_ctx);
1769
1770
CLProgramFree
Removes an OpenCL program.
void CLProgramFree(
int program
);
Parameters
program
[in] Handle of the OpenCL object.
Return Value
None. In the case of an internal error the value of _LastError changes. For information about the
error, use the GetLastError() function.
1771
CLKernelCreate
Creates the OpenCL program kernel and returns its handle.
int CLKernelCreate(
int
program,
// Kernel name
);
Parameters
program
[in] Handle to an object of the OpenCL program.
kernel_name
[in] The name of the kernel function in the appropriate OpenCL program, in which execution
begins.
Return Value
A handle to an OpenCL object if successful. In case of error -1 is returned. For information about
the error, use the GetLastError() function.
Note
At the moment, the following error codes are used:
ERR_OPENCL_INVALID_HANDLE - invalid handle to OpenCL program.
ERR_INVALID_PARAMETER - invalid string parameter.
ERR_OPENCL_TOO_LONG_KERNEL_NAME - kernel name contains more than 127 characters.
ERR_OPENCL_KERNEL_CREATE - internal error occurred while creating an OpenCL object.
1772
CLKernelFree
Removes an OpenCL start function.
void CLKernelFree(
int kernel
);
Parameters
kernel_name
[in] Handle of the kernel object.
Return Value
None. In the case of an internal error the value of _LastError changes. For information about the
error, use the GetLastError() function.
1773
CLSetKernelArg
Sets a parameter for the OpenCL function.
bool CLSetKernelArg(
int
kernel,
uint
arg_index,
void arg_value
// Source code
);
Parameters
kernel
[in] Handle to a kernel of the OpenCL program.
arg_index
[in] The number of the function argument, numbering starts with zero.
arg_value
[in] The value of the function argument.
Return Value
Returns true if successful, otherwise returns false. For information about the error, use the
GetLastError() function.
Note
At the moment, the following error codes are used:
ERR_INVALID_PARAMETER,
ERR_OPENCL_INVALID_HANDLE invalid handle to the OpenCL kernel.
ERR_OPENCL_SET_KERNEL_PARAMETER - internal error of OpenCL.
1774
CLSetKernelArgMem
Sets an OpenCL buffer as a parameter of the OpenCL function.
bool CLSetKernelArgMem(
int
kernel,
uint
arg_index,
int
cl_mem_handle
);
Parameters
kernel
[in] Handle to a kernel of the OpenCL program.
arg_index
[in] The number of the function argument, numbering starts with zero.
cl_mem_handle
[in] A handle to an OpenCL buffer.
Return Value
Returns true if successful, otherwise returns false. For information about the error, use the
GetLastError() function.
1775
CLBufferCreate
Creates an OpenCL buffer and returns its handle.
int CLBufferCreate(
int
context,
uint
size,
// Buffer size
uint flags
);
Parameters
context
[in] A handle to context OpenCL.
size
[in] Buffer size in bytes.
flags
[in] Buffer properties that are set using a combination of flags:CL_MEM_READ_WRITE,
CL_MEM_WRITE_ONLY, CL_MEM_READ_ONLY, CL_MEM_ALLOC_HOST_PTR.
Return Value
A handle to an OpenCL buffer if successful. In case of error -1 is returned. For information about the
error, use the GetLastError() function.
Note
At the moment, the following error codes are used:
ERR_OPENCL_INVALID_HANDLE - invalid handle to OpenCL context.
ERR_NOT_ENOUGH_MEMORY insufficient memory.
ERR_OPENCL_BUFFER_CREATE internal error creating buffers.
1776
CLBufferFree
Deletes an OpenCL buffer.
void CLBufferFree(
int
buffer
);
Parameters
buffer
[in] A handle to an OpenCL buffer.
Return Value
None. In the case of an internal error the value of _LastError changes. For information about the
error, use the GetLastError() function.
1777
CLBufferWrite
Writes into the OpenCL buffer and returns the number of written elements.
uint CLBufferWrite(
int
buffer,
// An array of values
uint
buffer_offset=0,
uint
data_offset=0,
uint
data_count=WHOLE_ARRAY
);
Parameters
buffer
[in] A handle of the OpenCL buffer.
data[]
[in] An array of values that should be written in the OpenCL buffer. Passed by reference.
buffer_offset
[in] An offset in the OpenCL buffer in bytes, from which writing begins. By default, writing start
with the very beginning of the buffer.
data_offset
[in] The index of the first array element, starting from which values from the array are written in
the OpenCL buffer. By default, values from the very beginning of the array are taken.
data_count
[in] The number of values that should be written. All the values of the array, by default.
Return Value
The number of written elements. 0 is returned in case of an error. For information about the error,
use the GetLastError() function.
Note
For one-dimensional arrays, the number of the element, with which reading of data for writing into
an OpenCL buffer begins, is calculated taking into account the AS_SERIES flags.
An array of two or more dimensions is presented as one-dimensional. In this case, data_offset is the
number of elements that should be skipped in the presentation, not the number of elements in the
first dimension.
1778
CLBufferRead
Reads an OpenCL buffer into an array and returns the number of read elements.
uint CLBufferRead(
int
buffer,
// An array of values
uint
buffer_offset=0,
uint
data_offset=0,
uint
data_count=WHOLE_ARRAY
);
Parameters
buffer
[in] A handle of the OpenCL buffer.
data[]
[in] An array for receiving values from the OpenCL buffer. Passed by reference.
buffer_offset
[in] An offset in the OpenCL buffer in bytes, from which reading begins. By default, reading start
with the very beginning of the buffer.
data_offset
[in] The index of the first array element for writing the values of the OpenCL buffer. By default,
writing of the read values into an array starts from the zero index.
data_count
[in] The number of values that should be read. The whole OpenCL buffer is read by default.
Return Value
The number of read elements. 0 is returned in case of an error. For information about the error, use
the GetLastError() function.
Note
For one-dimensional arrays, the number of the element, into which writing of data into an OpenCL
buffer begins, is calculated taking into account the AS_SERIES flags.
An array of two or more dimensions is presented as one-dimensional. In this case, data_offset is the
number of elements that should be skipped in the presentation, not the number of elements in the
first dimension.
1779
CLExecute
The function runs an OpenCL program. There are 3 versions of the function:
1. Launching kernel functions using one kernel
bool CLExecute(
int
kernel
);
2. Launching several kernel copies (OpenCL function) with task space description
bool CLExecute(
int
kernel,
uint
work_dim,
);
3. Launching several kernel copies (OpenCL function) with task space description and specification of
the size of the group's local task subset
bool CLExecute(
int
kernel,
uint
work_dim,
);
Parameters
kernel
[in] Handle to the OpenCL kernel.
work_dim
[in] Dimension of the tasks space.
global_work_offset[]
[in] Initial offset in the tasks space.
global_work_size[]
[in] The size of a subset of tasks.
local_work_size[]
[in] The size of the group's local task subset.
Return Value
Returns true if successful, otherwise returns false. For information about the error, use the
GetLastError() function.
Note
1780
global_work_size[3] array can be {40, 100, 320}. Then we have work_items[40, 100, 320]. So, the
total number of tasks is 40 x 100 x 320 = 1 280 000.
local_work_size[] sets the subset of the tasks that will be executed by the specified kernel of
OpenCL program. Its size is equal to work_items[] size and allows to split the common task subset
into smaller subsets without loss of remainder in division. In fact, the size of local_work_size[]
array should be selected so that the work_items[] global task set will be split into smaller subsets.
In this example local_work_size[3]={10, 10, 10} will be OK, as work_items[40, 100, 320] can be
gathered from local_items[10, 10, 10] array without division remainder.
1781
Standard Library
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) for end users. Library provides convenient access to the most of the internal MQL5
functions.
MQL5 Standard Library is placed in the working directory of the terminal in the 'Include' folder.
Section
Location
Base class
Include\
Classes of data
Include\Arrays\
Include\Files\
Include\Strings\
Include\Objects\
Include\Canvas\
Include\Charts\
Technical indicators
Include\Indicators\
Trade classes
Include\Trade\
Include\Expert\
Include\Controls\
1782
Standard Library
Description
Class CObject allows all its descendants to be part of a linked list. Also, a number of virtual methods
for further implementation in descendant classes are identified.
Declaration
class CObject
Title
#include <Object.mqh>
Prev
Next
Next
Compare methods
virtual Compare
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CArray
CChartObject
CChart
CString
CFile
CList
CTreeNode
1783
Standard Library
Prev
Gets a pointer to the previous element in the list.
CObject* Prev()
Return Value
Pointer to the previous element in the list. If an item is listed first, then return NULL.
Example:
//--- example for CObject::Prev()
#include <Object.mqh>
//--void OnStart()
{
CObject *object_first,*object_second;
//--object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use prev object
CObject *object=object_second.Prev();
//--- delete objects
delete object_first;
delete object_second;
}
1784
Standard Library
Prev
Sets the pointer to the previous element in the list.
void Prev(
CObject* object
Parameters
object
[in] New value of the pointer to the previous element in the list.
Example:
//--- example for CObject::Prev(CObject*)
#include <Object.mqh>
//--void OnStart()
{
CObject *object_first,*object_second;
//--object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use objects
//--- ...
//--- delete objects
delete object_first;
delete object_second;
}
1785
Standard Library
Next
Gets a pointer to the next element in the list.
CObject* Next()
Return Value
Pointer to the next element in the list. If this is the last element in the list, return NULL.
Example:
//--- example for CObject::Next()
#include <Object.mqh>
//--void OnStart()
{
CObject *object_first,*object_second;
//--object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use next object
CObject *object=object_first.Next();
//--- delete objects
delete object_first;
delete object_second;
}
1786
Standard Library
Next
Sets the pointer to the next element in the list.
void Next(
CObject* object
Parameters
object
[in] New value of the pointer to the next element in the list.
Example:
//--- example for CObject::Next(CObject*)
#include <Object.mqh>
//--void OnStart()
{
CObject *object_first,*object_second;
//--object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use objects
//--- ...
//--- delete objects
delete object_first;
delete object_second;
}
1787
Standard Library
Compare
Compares the data on a list element with data on another list element.
virtual int Compare(
const CObject* node,
// element
const int
// variant
mode=0
) const
Parameters
node
[in] Pointer to a list element to compare
mode=0
[in] Comparison variant
Return Value
0 - in case the list elements are equal, -1 - if the list element is less than the element used for
comparison (node), 1 - if the list element is greater than the element used for comparison (node).
Note
Compare() method in CObject class always returns 0 and does not perform any action. If you want to
compare data in derived class, the Compare(...) method should be implemented. The 'mode'
parameter should be used when implementing multivariate comparison.
Example:
//--- example for CObject::Compare(...)
#include <Object.mqh>
//--void OnStart()
{
CObject *object_first,*object_second;
//--object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
1788
Standard Library
object_second.Prev(object_first);
//--- compare objects
int result=object_first.Compare(object_second);
//--- delete objects
delete object_first;
delete object_second;
}
1789
Standard Library
Save
Saves list element data in a file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] Handle of the binary file opened earlier using the FileOpen () function
Return Value
true - successfully completed, false - error.
Note
Save(int) method in CObject class always returns 'true' and does not perform any action. If you want
to save the data of a derived class in a file, the Save(int) method should be implemented.
Example:
//--- example for CObject::Save(int)
#include <Object.mqh>
//--void OnStart()
{
int
file_handle;
1790
Standard Library
FileClose(file_handle);
}
delete object;
}
1791
Standard Library
Load
Loads list element data from a file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file opened earlier using the FileOpen() function.
Return Value
true successfully completed, false - error.
Note
Load(int) method in the CObject class always returns 'true' and does not perform any action. If you
want to load the data of a derived class from a file, the Load(int) method should be implemented.
Example:
//--- example for CObject::Load(int)
#include <Object.mqh>
//--void OnStart()
{
int
file_handle;
1792
Standard Library
//--- use object
//--- . . .
delete object;
}
1793
Standard Library
Type
Gets the type identifier.
virtual int Type() const
Return Value
Type identifier (for CObject - 0).
Example:
//--- example for CObject::Type()
#include <Object.mqh>
//--void OnStart()
{
CObject *object=new CObject;
//--object=new CObject;
if(object ==NULL)
{
printf("Object create error");
return;
}
//--- get objects type
int type=object.Type();
//--- delete object
delete object;
}
1794
Standard Library
Data Structures
This section contains the technical details on 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 data arrays 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 located in the working directory of the terminal
in the Include\Arrays folder.
Class
Description
CArrayChar
CArrayShort
CArrayInt
CArrayLong
CArrayFloat
CArrayDouble
CArrayString
CTreeNode
CTree
1795
Standard Library
CArray
CArray class is the base class of a dynamic array of variables.
Description
Class CArray is intended to operate on dynamic arrays of variables: memory allocation, sorting, and
working with files.
Declaration
class CArray : public CObject
Title
#include <Arrays\Array.mqh>
Step
Total
Available
Max
IsSorted
SortMode
Clear methods
Clear
Sort methods
Sort
Input/output
virtual Save
virtual Load
Derived classes:
CArrayChar
1796
Standard Library
CArrayShort
CArrayInt
CArrayLong
CArrayFloat
CArrayDouble
CArrayString
CArrayObj
1797
Standard Library
Step
Gets the increment size of the array.
int Step() const
Return Value
Increment size of the array.
Example:
//--- example for CArray::Step()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get resize step
int step=array.Step();
//--- use array
//--- ...
//--- delete array
delete array;
}
1798
Standard Library
Step
Sets the increment size of the array.
bool Step(
int step
// step
Parameters
step
[in] The new value of the increment size of the array.
Return Value
true - successful, false - there was an attempt to establish a step less than or equal to zero.
Example:
//--- example for CArray::Step(int)
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- set resize step
bool result=array.Step(1024);
//--- use array
//--- ...
//--- delete array
delete array;
}
1799
Standard Library
Total
Gets the number of elements in the array.
int Total() const;
Return Value
Number of elements in the array.
Example:
//--- example for CArray::Total()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- check total
int total=array.Total();
//--- use array
//--- ...
//--- delete array
delete array;
}
1800
Standard Library
Available
Gets the number of free elements of the array that are available without additional memory allocation.
int Available() const
Return Value
Number of free elements of the array available without additional memory allocation.
Example:
//--- example for CArray::Available()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- check available
int available=array.Available();
//--- use array
//--- ...
//--- delete array
delete array;
}
1801
Standard Library
Max
Gets the maximum possible size of the array without memory reallocation.
int Max() const
Return Value
The maximum possible size of the array without memory reallocation.
Example:
//--- example for CArray::Max()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- check maximum size
int max=array.Max();
//--- use array
//--- ...
//--- delete array
delete array;
}
1802
Standard Library
IsSorted
Gets the flag of array being sorted using the specified sorting mode.
bool IsSorted(
int mode=0
// sorting mode
) const
Parameters
mode=0
[in] Tested sorting mode.
Return Value
Flag of the sorted list. If the list is sorted using the specified mode - true, otherwise - false.
Note
The sort flag cannot be changed directly. It is set by the Sort() method and reset by any add/insert
method except for the InserSort(...).
Example:
//--- example for CArray::IsSorted()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- check sorted
if(array.IsSorted())
{
//--- use methods for sorted array
//--- ...
}
//--- delete array
delete array;
}
1803
Standard Library
SortMode
Gets the sorting mode for an array.
int SortMode() const;
Return Value
Sorting mode.
Example:
//--- example for CArray::SortMode()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- check sort mode
int sort_mode=array.SortMode();
//--- use array
//--- ...
//--- delete array
delete array;
}
1804
Standard Library
Clear
Deletes all of the array elements without memory release.
void Clear()
Return Value
None.
Example:
//--- example for CArray::Clear()
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- use array
//--- ...
//--- clear array
array.Clear();
//--- delete array
delete array;
}
1805
Standard Library
Sort
Sorts an array using 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 'mode' parameter is not used. For the CArrayObj array, multivariate sorting should be
implemented in the Sort(int) method of derived classes.
Example:
//--- example for CArray::Sort(int)
#include <Arrays\Array.mqh>
//--void OnStart()
{
CArray *array=new CArray;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- sorting by mode 0
array.Sort(0);
//--- use array
//--- ...
//--- delete array
delete array;
}
1806
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of a binary file previously opened using the FileOpen(...) function.
Return Value
true - successfully completed, false - error.
Example:
//--- example for CArray::Save(int)
#include <Arrays\Array.mqh>
//--void OnStart()
{
int
file_handle;
1807
Standard Library
Load
Loads data array from a file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of a binary file previously opened using the FileOpen () function.
Return Value
true - successfully completed, false - error.
Example:
//--- example for CArray::Load(...)
#include <Arrays\Array.mqh>
//--void OnStart()
{
int
file_handle;
1808
Standard Library
CArrayChar
CArrayChar is a class of dynamic array of char or uchar variables.
Description
CArrayChar class provides the ability to work with a dynamic array of char or uchar variables. The class
allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayChar : public CArray
Title
#include <Arrays\ArrayChar.mqh>
Class Methods
Memory control
Reserve
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Modify methods
Update
1809
Standard Library
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
1810
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is increased by the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayChar::Reserve(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1811
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayChar::Resize(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
1812
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayChar::Shutdown()
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
1813
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayChar::Add(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1814
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const char& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayChar::AddArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//--char src[];
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1815
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayChar* src
Parameters
src
[in] Pointer to an instance of CArrayChar class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayChar::AddArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
1816
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
1817
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
char element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into the array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayChar::Insert(char,int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1818
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const char& src[],
// source array
int
// position
pos
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayChar::InsertArray(const char &[],int)
#include <Arrays\ArrayChar.mqh>
//--char src[];
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1819
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayChar* src,
int
// position
pos
Parameters
src
[in] Pointer to an instance of the CArrayChar class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayChar::InsertArray(const CArrayChar*,int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
1820
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1821
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const char& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayChar::AssignArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//--char src[];
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1822
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayChar* src
Parameters
src
[in] Pointer to an instance of the CArrayChar class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayChar::AssignArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src
=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays are identical
//--- delete source array
1823
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1824
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
char element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayChar::Update(int,char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,'A'))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
1825
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayChar::Shift(int,int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
1826
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayChar::Delete(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1827
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayChar::DeleteRange(int,int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1828
Standard Library
At
Gets the element from the specified array position.
char At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, CHAR_MAX - there was an attempt to get an element from a
non-existing position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, CHAR_MAX may be a valid value of an array element. Therefore, always check the last
error code after receiving such a value.
Example:
//--- example for CArrayChar::At(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
char result=array.At(i);
if(result==CHAR_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
1829
Standard Library
//--- delete array
delete array;
}
1830
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const char& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayChar::CompareArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//--char src[];
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
1831
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const CArrayChar* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayChar class used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayChar::CompareArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
1832
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayChar::InsertSort(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort('A'))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
1833
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::Search(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search('A')!=-1) printf("Element found");
else
1834
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - the element not found.
Example:
//--- example for CArrayChar::SearchGreat(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat('A')!=-1) printf("Element found");
else
1835
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::SearchLess(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess('A')!=-1) printf("Element found");
else
1836
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::SearchGreatOrEqual(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual('A')!=-1) printf("Element found");
else
1837
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::SearchLessOrEqual(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual('A')!=-1) printf("Element found");
else
1838
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::SearchFirst(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst('A')!=-1) printf("Element found");
else
1839
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayChar::SearchLast(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast('A')!=-1) printf("Element found");
else
1840
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
char element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayChar::SearchLinear(char)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear('A')!=-1) printf("Element found");
else
1841
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayChar::Save(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
int
file_handle;
1842
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayChar::Load(int)
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
int
file_handle;
1843
Standard Library
}
//--- delete array
delete array;
}
1844
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayChar - 77).
Example:
//--- example for CArrayChar::Type()
#include <Arrays\ArrayChar.mqh>
//--void OnStart()
{
CArrayChar *array=new CArrayChar;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
1845
Standard Library
CArrayShort
CArrayShort is a class of dynamic array of short or ushort variables.
Description
Class CArrayShort provides the ability to work with a dynamic array of short or ushort variables. The
class allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayShort : public CArray
Title
#include <Arrays\ArrayShort.mqh>
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
Update
1846
Standard Library
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
1847
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayShort::Reserve(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1848
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayShort::Resize(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
1849
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayShort::Shutdown()
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
1850
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayShort::Add(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1851
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const short& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayShort::AddArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//--short src[];
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1852
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayShort* src
Parameters
src
[in] Pointer to an instance of CArrayShort class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayShort::AddArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
1853
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
1854
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
short element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into the array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayShort::Insert(short,int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1855
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const short& src[],
int
pos
// source array
// position
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayShort::InsertArray(const short &[],int)
#include <Arrays\ArrayShort.mqh>
//--short src[];
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1856
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayShort* src,
int
pos
Parameters
src
[in] Pointer to an instance of the CArrayShort class used as a source of elements to insert.
pos
[in] Position in the array to insert.
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayShort::InsertArray(const CArrayShort*,int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
1857
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1858
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const short& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayShort::AssignArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//--short src[];
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1859
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayShort* src
Parameters
src
[in] Pointer to an instance of the CArrayShort class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayShort::AssignArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src
=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
1860
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1861
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
short element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayShort::Update(int,short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
1862
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayShort::Shift(int,int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
1863
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayShort::Delete(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1864
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayShort::DeleteRange(int,int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1865
Standard Library
At
Gets the element from the specified array position.
short At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, SHORT_MAX - there was an attempt to get an element from a
non-existing position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, SHORT_MAX may be a valid value of an array element. Therefore, always check the last
error code after receiving such a value.
Example:
//--- example for CArrayShort::At(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
short result=array.At(i);
if(result==SHORT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
1866
Standard Library
//--- delete array
delete array;
}
1867
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const short& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayShort::CompareArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//--short src[];
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
1868
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const CArrayShort* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayShort class used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayShort::CompareArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
1869
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayShort::InsertSort(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
1870
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::Search(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100)!=-1) printf("Element found");
else
1871
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - element not found.
Example:
//--- example for CArrayShort::SearchGreat(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100)!=-1) printf("Element found");
else
1872
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::SearchLess(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100)!=-1) printf("Element found");
else
1873
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::SearchGreatOrEqual(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100)!=-1) printf("Element found");
else
1874
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::SearchLessOrEqual(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100)!=-1) printf("Element found");
else
1875
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::SearchFirst(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100)!=-1) printf("Element found");
else
1876
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayShort::SearchLast(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100)!=-1) printf("Element found");
else
1877
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
short element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayShort::SearchLinear(short)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear(100)!=-1) printf("Element found");
else
1878
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayShort::Save(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
int
file_handle;
1879
Standard Library
}
delete array;
}
1880
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayShort::Load(int)
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
int
file_handle;
1881
Standard Library
}
delete array;
}
1882
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayShort - 82).
Example:
//--- example for CArrayShort::Type()
#include <Arrays\ArrayShort.mqh>
//--void OnStart()
{
CArrayShort *array=new CArrayShort;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
1883
Standard Library
CArrayInt
CArrayInt is a class of dynamic array of int or uint variables.
Description
The class CArrayInt provides the ability to work with a dynamic array of int or uint variables. The class
allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayInt : public CArray
Title
#include <Arrays\ArrayInt.mqh>
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
Update
1884
Standard Library
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
1885
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayInt::Reserve(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1886
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayInt::Resize(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
1887
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayInt::Shutdown()
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
1888
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayInt::Add(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1889
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const int& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayInt::AddArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//--int src[];
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1890
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayInt* src
Parameters
src
[in] Pointer to an instance of CArrayInt class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayInt::AddArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
1891
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
1892
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
int element,
// element to insert
int pos
// position
Parameters
element
[in] Value of the element to be inserted into the array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayInt::Insert(int,int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1893
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const int& src[],
int
pos
// source array
// position
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayInt::InsertArray(const int &[],int)
#include <Arrays\ArrayInt.mqh>
//--int src[];
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1894
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayInt* src,
int
pos
Parameters
src
[in] Pointer to an instance of the CArrayInt class used as a source of elements to insert.
pos
[in] Position in the array to insert.
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayInt::InsertArray(const CArrayInt*,int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
1895
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1896
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const int& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayInt::AssignArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//--int src[];
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1897
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayInt* src
Parameters
src
[in] Pointer to an instance of the CArrayInt class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayInt::AssignArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src
=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
1898
Standard Library
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1899
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int pos,
// position
int element
// value
Parameters
pos
[in] Position of the element in the array to change.
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayInt::Update(int,int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,10000))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
1900
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayInt::Shift(int,int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
1901
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayInt::Delete(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1902
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayInt::DeleteRange(int,int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1903
Standard Library
At
Gets the element from the specified array position.
int At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, INT_MAX - there was an attempt to get an element from a nonexisting position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, INT_MAX may be a valid value of an array element. Therefore, always check the last error
code after receiving such a value.
Example:
//--- example for CArrayInt::At(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
int result=array.At(i);
if(result==INT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
1904
Standard Library
//--- delete array
delete array;
}
1905
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const int& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayInt::CompareArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//--int src[];
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
1906
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const CArrayInt* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayInt class used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayInt::CompareArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
1907
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayInt::InsertSort(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(10000))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
1908
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::Search(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(10000)!=-1) printf("Element found");
else
1909
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::SearchGreat(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(10000)!=-1) printf("Element found");
else
1910
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::SearchLess(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(10000)!=-1) printf("Element found");
else
1911
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of the sample in the sorted
array.
int SearchGreatOrEqual(
int element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::SearchGreatOrEqual(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(10000)!=-1) printf("Element found");
else
1912
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::SearchLessOrEqual(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(10000)!=-1) printf("Element found");
else
1913
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt:: SearchFirst(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(10000)!=-1) printf("Element found");
else
1914
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayInt::SearchLast(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(10000)!=-1) printf("Element found");
else
1915
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
int element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayInt::SearchLinear(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear(10000)!=-1) printf("Element found");
else
1916
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayInt::Save(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
int
file_handle;
1917
Standard Library
}
delete array;
}
1918
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayInt::Load(int)
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
int
file_handle;
1919
Standard Library
}
delete array;
}
1920
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayInt - 82).
Example:
//--- example for CArrayInt::Type()
#include <Arrays\ArrayInt.mqh>
//--void OnStart()
{
CArrayInt *array=new CArrayInt;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
1921
Standard Library
CArrayLong
CArrayLong class is a class of dynamic array of long or ulong variables.
Description
The CArrayLong class provides the ability to work with a dynamic array of long or ulong variables. The
class allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayLong : public CArray
Title
#include <Arrays\ArrayLong.mqh>
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
Update
1922
Standard Library
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
1923
Standard Library
1924
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayLong::Reserve(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1925
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayLong::Resize(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
1926
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayLong::Shutdown()
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
1927
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayLong::Add(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1928
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const long& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayLong::AddArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//--long src[];
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1929
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayLong* src
Parameters
src
[in] Pointer to an instance of CArrayLong class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayLong::AddArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
1930
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
1931
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
long element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into the array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayLong::Insert(long,int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1932
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const long& src[],
int
pos
// source array
// position
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayLong::InsertArray(const long &[],int)
#include <Arrays\ArrayLong.mqh>
//--long src[];
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1933
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayLong* src,
int
pos
Parameters
src
[in] Pointer to an instance of the CArrayLong class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayLong::InsertArray(const CArrayLong*,int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
1934
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1935
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const long& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayLong::AssignArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//--long src[];
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1936
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayLong* src
Parameters
src
[in] Pointer to an instance of the CArrayLong class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayLong::AssignArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src
=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
1937
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1938
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
long element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayLong::Update(int,long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,1000000))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
1939
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayLong::Shift(int,int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
1940
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayLong::Delete(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1941
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayLong::DeleteRange(int,int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1942
Standard Library
At
Gets the element from the specified array position.
long At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, LONG_MAX - there was an attempt to get an element from a
non-existing position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, LONG_MAX may be a valid value of an array element. Therefore, always check the last
error code after receiving such a value.
Example:
//--- example for CArrayLong::At(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
long result=array.At(i);
if(result==LONG_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
1943
Standard Library
//--- delete array
delete array;
}
1944
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const long& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayLong::CompareArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//--long src[];
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
1945
Standard Library
CompareArrayconst
Compares the array with another one.
bool CompareArrayconst(
const CArrayLong* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayLong class used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayLong::CompareArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
1946
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayLong::InsertSort(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(1000000))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
1947
Standard Library
Search
Searches for an element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::Search(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(1000000)!=-1) printf("Element found");
else
1948
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchGreat(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(1000000)!=-1) printf("Element found");
else
1949
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchLess(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(1000000)!=-1) printf("Element found");
else
1950
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchGreatOrEqual(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(1000000)!=-1) printf("Element found");
else
1951
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchLessOrEqual(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(1000000)!=-1) printf("Element found");
else
1952
Standard Library
SearchFirst
Searches for the first element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchFirst(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(1000000)!=-1) printf("Element found");
else
1953
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayLong::SearchLast(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(1000000)!=-1) printf("Element found");
else
1954
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
long element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayLong::SearchLinear(long)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear(1000000)!=-1) printf("Element found");
else
1955
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayLong::Save(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
int
file_handle;
1956
Standard Library
}
delete array;
}
1957
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayLong::Load(int)
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
int
file_handle;
1958
Standard Library
}
delete array;
}
1959
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayLong - 84).
Example:
//--- example for CArrayLong::Type()
#include <Arrays\ArrayLong.mqh>
//--void OnStart()
{
CArrayLong *array=new CArrayLong;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
1960
Standard Library
CArrayFloat
CArrayFloat class is a class of dynamic array of float variables.
Description
The CArrayFloat class provides the ability to work with a dynamic array of float variables. The class
allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayFloat : public CArray
Title
#include <Arrays\ArrayFloat.mqh>
Memory control
Reserve
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
1961
Standard Library
Update
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
1962
Standard Library
virtual Type
1963
Standard Library
Delta
Sets the comparison tolerance.
void Delta(
float delta
// tolerance
Parameters
delta
[in] The new value of the comparison tolerance.
Return Value
None
Note
Comparison tolerance is used in the search. Values are considered equal if their difference is less
than or equal to tolerance. The default tolerance is 0.0.
Example:
//--- example for CArrayFloat::Delta(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- set compare variation
array.Delta(0.001);
//--- use array
//--- . . .
//--- delete array
delete array;
}
1964
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayFloat::Reserve(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1965
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayFloat::Resize(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
1966
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayFloat::Shutdown()
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
1967
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayFloat::Add(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1968
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const float& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayFloat::AddArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//--float src[];
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1969
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayFloat* src
Parameters
src
[in] Pointer to an instance of CArrayFloat class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayFloat::AddArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
1970
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
1971
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
float element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayFloat::Insert(float,int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1972
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const float& src[],
int
pos
// source array
// position
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayFloat::InsertArray(const float &[],int)
#include <Arrays\ArrayFloat.mqh>
//--float src[];
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1973
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayFloat* src,
int
pos
Parameters
src
[in] Pointer to an instance of the CArrayFloat class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayFloat::InsertArray(const CArrayFloat*,int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
1974
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1975
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const float& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayFloat::AssignArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//--float src[];
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
1976
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayFloat* src
Parameters
src
[in] Pointer to an instance of the CArrayFloat class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayFloat::AssignArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src
=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
1977
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
1978
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
float element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayFloat::Update(int,float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100.0))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
1979
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayFloat::Shift(int,int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
1980
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayFloat::Delete(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1981
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayFloat::DeleteRange(int,int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
1982
Standard Library
At
Gets the element from the specified array position.
float At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, FLT_MAX - there was an attempt to get an element from a nonexisting position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, FLT_MAX may be a valid value of an array element. Therefore, always check the last
error code after receiving such a value.
Example:
//--- example for CArrayFloat::At(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
float result=array.At(i);
if(result==FLT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
1983
Standard Library
//--- delete array
delete array;
}
1984
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const float& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayFloat::CompareArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//--float src[];
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
1985
Standard Library
AssignArrayconst
Compares the array with another one.
bool AssignArrayconst(
const CArrayFloat* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayFloat class used as a source of elements for comparison.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayFloat::CompareArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
1986
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayFloat::InsertSort(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100.0))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
1987
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::Search(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100.0)!=-1) printf("Element found");
else
1988
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::SearchGreat(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100.0)!=-1) printf("Element found");
else
1989
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat:: SearchLess(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100.0)!=-1) printf("Element found");
else
1990
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::SearchGreatOrEqual(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found");
else
1991
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::SearchLessOrEqual(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found");
else
1992
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::SearchFirst(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100.0)!=-1) printf("Element found");
else
1993
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayFloat::SearchLast(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100.0)!=-1) printf("Element found");
else
1994
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
float element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayFloat::SearchLinear(float)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear(100.0)!=-1) printf("Element found");
else
1995
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayFloat::Save(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
int
file_handle;
1996
Standard Library
}
delete array;
}
1997
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayFloat::Load(int)
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
int
file_handle;
1998
Standard Library
}
delete array;
}
1999
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayFloat - 87).
Example:
//--- example for CArrayFloat::Type()
#include <Arrays\ArrayFloat.mqh>
//--void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
2000
Standard Library
CArrayDouble
CArrayDouble class is a class of dynamic array of double variables.
Description
The CArrayDouble class provides the ability to work with a dynamic array of double variables. The class
allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayDouble : public CArray
Title
#include <Arrays\ArrayDouble.mqh>
Memory control
Reserve
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
2001
Standard Library
Update
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Maximum
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
2002
Standard Library
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CIndicatorBuffer
2003
Standard Library
Delta
Sets the comparison tolerance.
void Delta(
double delta
// tolerance
Parameters
delta
[in] The new value of the comparison tolerance.
Return Value
No
Note
Comparison tolerance is used in the search. Values are considered equal if their difference is less
than or equal to tolerance. The default tolerance is 0.0.
Example:
//--- example for CArrayDouble::Delta(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- set compare variation
array.Delta(0.001);
//--- use array
//--- . . .
//--- delete array
delete array;
}
2004
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayDouble::Reserve(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2005
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayDouble::Resize(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
2006
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayDouble::Shutdown()
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
2007
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayDouble::Add(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2008
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const double& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayDouble::AddArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//--double src[];
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2009
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayDouble* src
Parameters
src
[in] Pointer to an instance of CArrayDouble class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayDouble::AddArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
2010
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
2011
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
double element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayDouble::Insert(double,int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2012
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const double& src[],
// source array
int
// position
pos
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayDouble::InsertArray(const double &[],int)
#include <Arrays\ArrayDouble.mqh>
//--double src[];
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2013
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayDouble* src,
int
// position
pos
Parameters
src
[in] Pointer to an instance of the CArrayDouble class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayDouble::InsertArray(const CArrayDouble*,int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
2014
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2015
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const double& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayDouble::AssignArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//--double src[];
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2016
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayDouble* src
Parameters
src
[in] Pointer to an instance of the CArrayDouble class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayDouble::AssignArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src
=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
2017
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2018
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
double element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element.
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayDouble::Update(int,double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100.0))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
2019
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayDouble::Shift(int,int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
2020
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayDouble::Delete(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2021
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayDouble::DeleteRange(int,int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2022
Standard Library
At
Gets the element from the specified array position.
double At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, DBL_MAX - there was an attempt to get an element from a nonexisting position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, DBL_MAX may be a valid value of an array element. Therefore, always check the last
error code after receiving such a value.
Example:
//--- example for CArrayDouble::At(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
double result=array.At(i);
if(result==DBL_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//---
2023
Standard Library
//--- delete array
delete array;
}
2024
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const double& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayDouble::CompareArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//--double src[];
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
2025
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const CArrayDouble* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayDouble class used as a source of elements for comparison.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayDouble::CompareArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
2026
Standard Library
Minimum
Gets index of the lowest element of the array in the specified range.
int Minimum(
int start,
// starting index
int count
// number of elements
) const
Parameters
start
[in] Starting index of the search range.
count
[in] Search range size (number of elements).
Return Value
Index of the lowest element in the specified range.
2027
Standard Library
Maximum
Gets index of the highest element of the array in the specified range.
int Maximum(
int start,
// starting index
int count
// number of elements
) const
Parameters
start
[in] Starting index of the search range.
count
[in] Search range size (number of elements).
Return Value
Index of the highest element in the specified range.
2028
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayDouble::InsertSort(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100.0))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
2029
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::Search(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100.0)!=-1) printf("Element found");
else
2030
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::SearchGreat(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100.0)!=-1) printf("Element found");
else
2031
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble:: SearchLess(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100.0)!=-1) printf("Element found");
else
2032
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::SearchGreatOrEqual(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found");
else
2033
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::SearchLessOrEqual(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found");
else
2034
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::SearchFirst(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100.0)!=-1) printf("Element found");
else
2035
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayDouble::SearchLast(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100.0)!=-1) printf("Element found");
else
2036
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
double element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayDouble::SearchLinear(double)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear(100.0)!=-1) printf("Element found");
else
2037
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayDouble::Save(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
int
file_handle;
2038
Standard Library
}
//--- delete array
delete array;
}
2039
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayDouble::Load(int)
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
int
file_handle;
2040
Standard Library
}
//--- delete array
delete array;
}
2041
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayDouble - 87).
Example:
//--- example for CArrayDouble::Type()
#include <Arrays\ArrayDouble.mqh>
//--void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
2042
Standard Library
CArrayString
CArrayString class is a class of dynamic array of string variables.
Description
The CArrayString class provides the ability to work with a dynamic array of string variables. The class
allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
Declaration
class CArrayString : public CArray
Title
#include <Arrays\ArrayString.mqh>
Resize
Shutdown
Add methods
Add
AddArray
AddArray
Insert
InsertArray
InsertArray
AssignArray
AssignArray
Update methods
Update
2043
Standard Library
Shift
Delete methods
Delete
DeleteRange
Access methods
At
Compare methods
CompareArray
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
SearchLinear
Input/output
virtual Save
virtual Load
virtual Type
2044
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayString::Reserve(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2045
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. To reduce fragmentation of memory, the array size is changed by the step previously
determined by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayString::Resize(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
2046
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
Return Value
true - successful, false - error.
Example:
//--- example for CArrayString::Shutdown()
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
2047
Standard Library
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
true - successful, false - cannot add an element.
Example:
//--- example for CArrayString::Add(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(IntegerToString(i)))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2048
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const string& src[]
// source array
Parameters
src[]
[in] Reference to an array of source elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayString::AddArray(const string &[])
#include <Arrays\ArrayString.mqh>
//--string src[];
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2049
Standard Library
AddArray
Adds elements of one array to the end of another.
bool AddArray(
const CArrayString* src
Parameters
src
[in] Pointer to an instance of CArrayString class used as a source of elements to add.
Return Value
true - successful, false - cannot add items.
Example:
//--- example for CArrayString::AddArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
2050
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
2051
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
string element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayString::Insert(string,int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(IntegerToString(i),0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2052
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const string& src[],
int
// source array
pos
// position
Parameters
src[]
[in] Reference to an array used as a source of elements to insert
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayString::InsertArray(const string &[],int)
#include <Arrays\ArrayString.mqh>
//--string src[];
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2053
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
CArrayString* src,
int
pos
Parameters
src
[in] Pointer to an instance of the CArrayString class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Example:
//--- example for CArrayString::InsertArray(const CArrayString*,int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
2054
Standard Library
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2055
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const string& src[]
// source array
Parameters
src[]
[in] Reference to an array used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayString::AssignArray(const string &[])
#include <Arrays\ArrayString.mqh>
//--string src[];
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2056
Standard Library
AssignArray
Copies the elements of one array to another.
bool AssignArray(
const CArrayString* src
Parameters
src
[in] Pointer to an instance of the CArrayString class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Example:
//--- example for CArrayString::AssignArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src
=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
2057
Standard Library
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2058
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
string element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Example:
//--- example for CArrayString::Update(int, string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,"ABC"))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
2059
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayString::Shift(int,int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
2060
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Example:
//--- example for CArrayString::Delete(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2061
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove the elements.
Example:
//--- example for CArrayString::DeleteRange(int,int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2062
Standard Library
At
Gets the element from the specified array position.
string At(
int pos
// position
) const
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - success, ""- there was an attempt to get an element from a non-existing
position (the last error code is ERR_OUT_OF_RANGE).
Note
Of course, "" may be a valid value of an array element. Therefore, always check the last error code
after receiving such a value.
Example:
//--- example for CArrayString::At(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
string result=array.At(i);
if(result=="" && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
2063
Standard Library
//--- delete array
delete array;
}
2064
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const string& src[]
// source array
) const
Parameters
src[]
[in] Reference to an array used as a source of elements for comparison.
Return Value
true - arrays are equal, false - arrays are not equal.
Example:
//--- example for CArrayString::CompareArray(const string &[])
#include <Arrays\ArrayString.mqh>
//--string src[];
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}
2065
Standard Library
CompareArray
Compares the array with another one.
bool CompareArrays(
const CArrayString* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayString class used as a source of elements for comparison.
Return Value
true - successful, false - cannot copy the items.
Example:
//--- example for CArrayString::CompareArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
2066
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Example:
//--- example for CArrayString::InsertSort(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort("ABC"))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
2067
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString::Search(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search("ABC")!=-1) printf("Element found");
else
2068
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString::SearchGreat(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat("ABC")!=-1) printf("Element found");
else
2069
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString:: SearchLess(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess("ABC")!=-1) printf("Element found");
else
2070
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString:: SearchGreatOrEqual(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual("ABC")!=-1) printf("Element found");
else
2071
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString:: SearchLessOrEqual(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual("ABC")!=-1) printf("Element found");
else
2072
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString:: SearchFirst(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst("ABC")!=-1) printf("Element found");
else
2073
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayString:: SearchLast(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast("ABC")!=-1) printf("Element found");
else
2074
Standard Library
SearchLinear
Searches for the element equal to the sample in the array.
int SearchLinear(
string element
// sample
) const
Parameters
element
[in] The sample element to search in the array.
Return Value
The position of the found element - successful, -1 - the element not found.
Note
The method uses the linear search (or sequential search) algorithm for unsorted arrays.
Example:
//--- example for CArrayString::SearchLinear(string)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- search element
if(array.SearchLinear("ABC")!=-1) printf("Element found");
else
2075
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayString::Save(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
int
file_handle;
2076
Standard Library
}
delete array;
}
2077
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayString::Load(int)
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
int
file_handle;
2078
Standard Library
}
delete array;
}
2079
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayString - 89).
Example:
//--- example for CArrayString::Type()
#include <Arrays\ArrayString.mqh>
//--void OnStart()
{
CArrayString *array=new CArrayString;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
2080
Standard Library
CArrayObj
CArrayObj class is a class of dynamic array of pointers to instances of CObject and its derived classes.
Description
Class CArrayObj provides the ability to work with a dynamic array of pointers to instances of CObject
and its derived classes. This allows working both with multidimensional dynamic arrays of primitive
data types and with data structures that have more complex organization of data.
The class allows adding/inserting/deleting array elements, performing an array sorting, and searching
in a sorted array. In addition, methods of working with files have been implemented.
There are certain subtleties of the class CArrayObj.
Declaration
class CArrayObj : public CArray
Title
#include <Arrays\ArrayObj.mqh>
FreeMode
Memory control
Reserve
Resize
Shutdown
Add methods
Add
AddArray
Insert
InsertArray
2081
Standard Library
AssignArray
Update methods
Update
Shift
Delete methods
Detach
Delete
DeleteRange
Clear
Access methods
At
Compare methods
CompareArray
Search
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
2082
Standard Library
Input/output
Save
Load
Type
Derived classes:
CIndicator
CIndicators
Arrays of the CObject class have practical application (including all classes of the Standard Library).
For example, consider the options for two-dimensional array:
#include <Arrays\ArrayDouble.mqh>
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
int i,j;
int first_size=10;
int second_size=100;
//--- create array
CArrayObj
*array=new CArrayObj;
CArrayDouble *sub_array;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create subarrays
for(i=0;i<first_size;i++)
{
sub_array=new CArrayDouble;
if(sub_array==NULL)
{
delete array;
printf("Object create error");
return;
}
//--- fill array
for(j=0;j<second_size;j++)
{
sub_array.Add(i*j);
}
array.Add(sub_array);
}
2083
Standard Library
//--- 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 CArrayObj class:
1. Mechanism of memory management is enabled. (default)
In this case, CArrayObj takes responsibility for releasing the memory used for the elements after their
removal from the array. A custom program should not release 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);
//--- actions performed with the element
. . .
}
//--- remove the array with the elements
delete array;
2084
Standard Library
int i;
//--- create an array
CArrayObj *array=new CArrayObj;
//--- disable the mechanism of memory management
array.FreeMode(false);
//--- fill array with 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);
//--- actions performed with the element
. . .
}
//--- remove array elements
while(array.Total()) delete array.Detach();
//--- remove empty array
delete array;
2085
Standard Library
FreeMode
Gets the flag of memory management.
bool FreeMode() const
Return Value
Flag of memory management.
Example:
//--- example for CArrayObj::FreeMode()
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get free mode flag
bool array_free_mode=array.FreeMode();
//--- delete array
delete array;
}
2086
Standard Library
FreeMode
Sets the flag of memory management.
void FreeMode(
bool mode
// new flag
Parameters
mode
[in] New value of the memory management flag.
Return Value
None.
Note
Setting the memory management flag is an important part in the CArrayObj class use. 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
delete operator. 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 deallocated by the program afterwards.
If the user program resets the flag of memory management, the user must understand his
responsibility for the removal of the array before the termination of the program. Otherwise the
memory allocated for elements by the new operator is not released.
For large amounts of data this could lead even to crash of your terminal.
If the user does not reset the memory management flag, there is another pitfall. When pointer
elements in array are stored somewhere in the local variables, then removing the array will lead to a
critical error and crash of the user program. By default, the memory management flag is set, i.e.
the class of the array is responsible for freeing the memory elements.
Example:
//--- example for CArrayObj::FreeMode(bool)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- reset free mode flag
array.FreeMode(false);
2087
Standard Library
//--- use array
//--- . . .
//--- delete array
delete array;
}
2088
Standard Library
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 - successful, false - there was an attempt to request for an amount less than or equal to zero,
or failed to increase the array.
Note
To reduce fragmentation of memory, the array size is changed using the step previously determined
by the Step(int) method or the default step of 16.
Example:
//--- example for CArrayObj::Reserve(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2089
Standard Library
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 - successful, false - there was an attempt to set the size less than or equal to zero.
Note
Changing the size of the array allows using the memory optimally. Excessive elements on the right
are lost. The memory of the lost elements is released or not depending on the memory management
mode.
To reduce fragmentation of memory, change the size of the array is made with a step previously
given through the method of Step (int), or 16 (default).
Example:
//--- example for CArrayObj::Resize(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}
2090
Standard Library
Clear
Removes all elements of the array without the release of the memory array.
void Clear()
Return Value
No.
Note
If the memory management flag is enabled, the memory used for the deleted objects is released.
Example:
//--- example for CArrayObj::Clear()
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- clear array
array.Clear();
//--- delete array
delete array;
}
2091
Standard Library
Shutdown
Clears the array with full deallocation of memory for it (but not for its elements).
bool Shutdown()
Return Value
true - successful, false - an error occurred.
Note
If memory management is enabled, the memory of deleted elements is deallocated.
Example:
//--- example for CArrayObj::Shutdown()
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}
2092
Standard Library
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
true - successful, false - cannot create an element.
Note
Method CreateElement (int) in class CArrayObj always returns false and does not perform any action.
If necessary, the CreateElement(int) method should be implemented in a derived class.
Example:
//--- example for CArrayObj::CreateElement(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
int
size=100;
2093
Standard Library
}
2094
Standard Library
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
true - successful, false - cannot add an element.
Note
Element is not added to the array if an invalid pointer (such as NULL) is passed as a parameter.
Example:
//--- example for CArrayObj::Add(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(new CObject))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}
2095
Standard Library
AddArray
Adds elements from one array to the end of another.
bool AddArray(
const CArrayObj * src
Parameters
src
[in] Pointer to an instance of the CArrayDouble class - source of elements to add.
Return Value
true - successful, false - cannot add items.
Note
Adding elements from array to array is actually copying the pointers. Therefore, when calling the
method, there is a pitfall - there may be a pointer to a dynamic object in more than one variable.
//--- example
extern bool
make_error;
extern int
error;
//--- after removing the receiver array, it is possible to address an element by invalid p
break;
case 2:
2096
Standard Library
//--- disable the mechanism of memory management in the source array
src.FreeMode(false);
//--- disable the mechanism of memory management in the receiver array
array.FreeMode(false);
//--- result:
//--- after the program termination, get a "memory leak"
break;
}
}
else
{
//--- disable the mechanism of memory management in the source array
if(src.FreeMode()) src.FreeMode(false);
//--- delete the source array
delete src;
//--- result:
//--- addressing the receiver array element will be correct
//--- deleting the receiver array will lead to deleting its elements
}
Example:
//--- example for CArrayObj::AddArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- add another array
if(!array.AddArray(src))
2097
Standard Library
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2098
Standard Library
Insert
Inserts an element to the specified position in the array.
bool Insert(
CObject* element,
// element to insert
int
// position
pos
Parameters
element
[in] Value of the element to be inserted into an array
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert the element.
Note
Element is not added to the array if an invalid pointer (such as NULL) is passed as a parameter.
Example:
//--- example for CArrayObj::Insert(CObject*,int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(new CObject,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
2099
Standard Library
delete array;
}
2100
Standard Library
InsertArray
Inserts elements of one array from the specified position of another array.
bool InsertArray(
const CArrayObj* src,
int
// position
pos
Parameters
src
[in] Pointer to an instance of the CArrayObj class used as a source of elements to insert.
pos
[in] Position in the array to insert
Return Value
true - successful, false - cannot insert items.
Note
See: CArrayObj::AddArray(const CArrayObj*).
Example:
//--- example for CArrayObj::InsertArray(const CArrayObj*,int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- insert another array
2101
Standard Library
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;
}
2102
Standard Library
AssignArray
Compares the array with another one.
bool AssignArray(
const CArrayObj* src
Parameters
src
[in] Pointer to an instance of the CArrayObj class used as a source of elements to copy.
Return Value
true - successful, false - cannot copy the elements.
Note
If the receiver array is not empty when calling AssignArray, then all its elements will be removed;
and if the memory management flag is set, the memory used for the deleted elements will be
released. The receiver array becomes an exact copy of the source one. Additionally, see
CArrayObj::AddArray(const CArrayObj*).
Example:
//--- example for CArrayObj::AssignArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
2103
Standard Library
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}
2104
Standard Library
Update
Changes the element at the specified array position.
bool Update(
int
pos,
CObject* element
// position
// value
Parameters
pos
[in] Position of the element in the array to change
element
[in] New value of the element
Return Value
true - successful, false - cannot change the element.
Note
The element will not change if an invalid pointer (for example, NULL) is passed as a parameter. If
the memory management is enabled, the memory of a replaced element is deallocated.
Example:
//--- example for CArrayObj::Update(int,CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,new CObject))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}
2105
Standard Library
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 in the array
shift
[in] The shift value (both positive and negative).
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CArrayObj::Shift(int,int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}
2106
Standard Library
Detach
Removes an element from a given position in the array.
CObject* Detach(
int pos
// position
Parameters
pos
[in] Position of a removed item in the array.
Return Value
Pointer to the removed element - success, NULL - cannot remove the element.
Note
When an element is removed from the array, it will not be deleted regardless of the memory
management flag. Once the array element pointer is used, it has to be deallocated.
Example:
//--- example for CArrayObj::Detach(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
CObject *object=array.Detach(0);
if(object==NULL)
{
printf("Detach error");
delete array;
return;
}
//--- use element
//--- . . .
//--- delete element
delete object;
//--- delete array
delete array;
}
2107
Standard Library
Delete
Removes the element from the specified array position.
bool Delete(
int pos
// position
Parameters
pos
[in] Position of the array element to be removed.
Return Value
true - successful, false - cannot remove the element.
Note
If the memory management is enabled, the memory of deleted elements is deallocated.
Example:
//--- example for CArrayObj::Delete(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2108
Standard Library
DeleteRange
Deletes a group of elements from the specified array position.
bool DeleteRange(
int from,
int to
Parameters
from
[in] Position of the first array element to be removed.
to
[in] Position of the last array element to be removed.
Return Value
true - successful, false - cannot remove elements.
Note
If the memory management is enabled, the memory of deleted elements is deallocated.
Example:
//--- example for CArrayObj::DeleteRange(int,int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}
2109
Standard Library
At
Gets the element from the specified array position.
CObject* At(
int pos
// position
Parameters
pos
[in] Position of the desired element in the array.
Return Value
The value of the element - successful, NULL- there was an attempt to get an element of a nonexistent position.
Example:
//--- example for CArrayObj::At(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
CObject *result=array.At(i);
if(result==NULL)
{
//--- Error reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
delete array;
}
2110
Standard Library
CompareArray
Compares the array with another one.
bool CompareArray(
const CArrayObj* src
) const
Parameters
src
[in] Pointer to an instance of the CArrayObj class used as a source of elements for comparison.
Return Value
true - the arrays are equal - the arrays are not equal.
Example:
//--- example for CArrayObj::CompareArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- fill source array
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}
2111
Standard Library
InsertSort
Inserts an 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
true - successful, false - cannot insert the element.
Note
Element is not added to the array if an invalid pointer (such as NULL) is passed as a parameter.
Example:
//--- example for CArrayObj::InsertSort(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(new CObject))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}
2112
Standard Library
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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj::Search(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.Search(sample)!=-1) printf("Element found");
else
2113
Standard Library
SearchGreat
Searches for an element with a value exceeding the value of the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj::SearchGreat(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchGreat(sample)!=-1) printf("Element found");
else
2114
Standard Library
SearchLess
Searches for an element with a value less than the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj:: SearchLess(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLess(sample)!=-1) printf("Element found");
else
2115
Standard Library
SearchGreatOrEqual
Searches for an element with a value greater than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj::SearchGreatOrEqual(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchGreatOrEqual(sample)!=-1) printf("Element found");
else
2116
Standard Library
}
2117
Standard Library
SearchLessOrEqual
Searches for an element with a value less than or equal to the value of 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj:: SearchLessOrEqual(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLessOrEqual(sample)!=-1) printf("Element found");
else
2118
Standard Library
SearchFirst
Searches for 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj::SearchFirst(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchFirst(sample)!=-1) printf("Element found");
else
2119
Standard Library
SearchLast
Searches for the last element equal to the sample in the 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 - successful, -1 - the element not found.
Example:
//--- example for CArrayObj:: SearchLast(CObject*)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLast(sample)!=-1) printf("Element found");
else
2120
Standard Library
Save
Saves data array in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Example:
//--- example for CArrayObj::Save(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
int
file_handle;
2121
Standard Library
Load
Loads data array from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen(...) function.
Return Value
true successfully completed, false - error.
Note
When reading array elements from the file, the CArrayObj::CreateElement(int) method is called to
create each element.
Example:
//--- example for CArrayObj::Load(int)
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
int
file_handle;
2122
Standard Library
//--- use arrays elements
//--- . . .
//--- delete array
delete array;
}
2123
Standard Library
Type
Gets the array type identifier.
virtual int Type() const
Return Value
Array type identifier (for CArrayObj - 7778).
Example:
//--- example for CArrayObj::Type()
#include <Arrays\ArrayObj.mqh>
//--void OnStart()
{
CArrayObj *array=new CArrayObj;
//--if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}
2124
Standard Library
CList
CList Class is a class of dynamic list of instances of the CObject class and its derived classes.
Description
Class CList provides the ability to work with a list of instances of CObject and its derived classes. The
class allows adding/inserting/deleting array elements, performing an array sorting, and searching in a
sorted array. In addition, methods of working with files have been implemented.
There are some subtleties of working with the CList class. The class has a mechanism to control
dynamic memory, so be careful when working with elements of the list.
Subtleties of the mechanism of memory management similar to those described in CArrayObj.
Declaration
class CList : public CObject
Title
#include <Arrays\List.mqh>
FreeMode
Total
IsSorted
SortMode
Create methods
CreateElement
Add methods
Add
Insert
Delete methods
DetachCurrent
DeleteCurrent
2125
Standard Library
Delete
Clear
Navigation
IndexOf
GetNodeAtIndex
GetFirstNode
GetPrevNode
GetCurrentNode
GetNextNode
GetLastNode
Ordering methods
Sort
MoveToIndex
Exchange
Compare methods
CompareList
Search methods
Search
Input/output
virtual Save
virtual Load
virtual Type
2126
Standard Library
FreeMode
Gets the flag of memory management when deleting list elements.
bool FreeMode() const
Return Value
Flag of memory management.
Example:
//--- example for CList::FreeMode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- get free mode flag
bool list_free_mode=list.FreeMode();
//--- delete list
delete list;
}
2127
Standard Library
FreeMode
Sets the flag of memory management when deleting list elements.
void FreeMode(
bool mode
// new value
Parameters
mode
[in] New value of the memory management flag.
Note
Setting the memory management flag is an important part in the CList class use. Since the list
elements are pointers to dynamic objects, it is important to determine what to do with them when
removing from the list.
If the flag is set, when removing an element from the list, the element is automatically deleted by
the delete operator. 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 deallocated by the program afterwards.
If the user program resets the flag of memory management, users should understand their
responsibility for the removal of the list elements before the termination of the program.
Otherwise, the memory allocated for elements by the new operator is not released.
For large amounts of data this could lead even to a terminal crash.
If the user program does not reset the memory management flag, there is another "pitfall". When
pointer elements in list are stored somewhere in the local variables, then removing the list will lead
to a critical error and crash of the user program. By default, the memory management flag is set,
i.e. the class of the list is responsible for releasing the memory elements.
Example:
//--- example for CList::FreeMode(bool)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- reset free mode flag
list.FreeMode(false);
//--- use list
//--- . . .
//--- delete list
2128
Standard Library
delete list;
}
2129
Standard Library
Total
Gets the number of elements in the list.
int Total() const
Return Value
Number of elements in the list.
Example:
//--- example for CList::Total()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- check total
int total=list.Total();
//--- use list
//--- ...
//--- delete list
delete list;
}
2130
Standard Library
IsSorted
Gets the sorted list flag.
bool IsSorted(
int mode=0
// sorting mode
) const
Parameters
mode=0
[in] Checked sort mode.
Return Value
Flag of the sorted list. Returns true if the list is sorted using the specified mode, otherwise returns
false.
Note
Flag of the sorted list cannot be changed directly. The flag is set by Sort(int) and resets by any add/
insert methods.
Example:
//--- example for CList::IsSorted()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- check sorted
if(list.IsSorted(0))
{
//--- use methods for sorted list
//--- ...
}
//--- delete list
delete list;
}
2131
Standard Library
SortMode
Gets the version of the sorting.
int SortMode() const
Return Value
Sorting mode, or -1 if the list is not sorted.
Example:
//--- example for CList::SortMode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- check sort mode
int sort_mode=list.SortMode();
//--- use list
//--- ...
//--- delete list
delete list;
}
2132
Standard Library
CreateElement
Creates a new element of the list.
CObject* CreateElement()
Return Value
Pointer to the newly created element - successful, NULL - cannot create an element.
Note
Method CreateElement () in the CList class always returns NULL and does not perform any actions. If
necessary, method CreateElement () should be implemented in a derived class.
Example:
//--- example for CList::CreateElement(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
int
size=100;
2133
Standard Library
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
Index of the added element - success, -1 - error.
Note
The element is not added to the list, if an invalid pointer (for example, NULL) is passed as a
parameter.
Example:
//--- example for CList::Add(Cobject*)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add 100 elements
for(int i=0;i<100;i++)
{
if(list.Add(new CObject)==-1)
{
printf("Element addition error");
delete list;
return;
}
}
//--- use list
//--- . . .
//--- delete list
delete list;
}
2134
Standard Library
Insert
Inserts an element to the specified position in the list.
int Insert(
CObject* element,
// element to insert
int
// position
pos
Parameters
element
[in] value of the element to insert in the list
pos
[in] position in the list to insert
Return Value
index of inserted element - success, -1 - error.
Note
The element is not added to the list, if an invalid pointer (for example, NULL) is passed as a
parameter.
Example:
//--- example for CList::Insert(CObject*,int)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- insert 100 elements
for(int i=0;i<100;i++)
{
if(list.Insert(new CObject,0)==-1)
{
printf("Element insert error");
delete list;
return;
}
}
//--- use list
//--- . . .
2135
Standard Library
//--- delete list
delete list;
}
2136
Standard Library
DetachCurrent
Extracts an element from the current position in the list without its "physical" deletion.
CObject* DetachCurrent()
Return Value
Pointer to the removed element in case of success, NULL - cannot remove the element.
Note
When removed from the list, the element is not removed in any state of the memory management
flag. The pointer to the extracted element should be released after it has been used.
Example:
//--- example for CList::DetachCurrent()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.DetachCurrent();
if(object==NULL)
{
printf("Detach error");
delete list;
return;
}
//--- use element
//--- . . .
//--- delete element
delete object;
//--- delete list
delete list;
}
2137
Standard Library
DeleteCurrent
Removes the element from the current position in the list.
bool DeleteCurrent()
Return Value
true - successful, false - cannot remove the element.
Note
If the memory management is enabled, memory for the removed element is deallocated.
Example:
//--- example for CList::DeleteCurrent()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
if(!list.DeleteCurrent())
{
printf("Delete error");
delete list;
return;
}
//--- delete list
delete list;
}
2138
Standard Library
Delete
Removes the element from the given position in the list.
bool Delete(
int pos
// position
Parameters
pos
[in] position of element to be removed from the list.
Return Value
true - successful, false - cannot remove the element.
Note
If the memory management flag is enabled, the memory used for the deleted element is released.
Example:
//--- example for CList::Delete(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
if(!list.Delete(0))
{
printf("Delete error");
delete list;
return;
}
//--- delete list
delete list;
}
2139
Standard Library
Clear
Removes all elements of the list.
void Clear()
Note
If the memory management is enabled, the memory of deleted elements is deallocated.
Example:
//--- example for CList::Clear()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
//--- clear list
list.Clear();
//--- delete list
delete list;
}
2140
Standard Library
IndexOf
Gets the index of the specified list element.
int IndexOf(
CObject* element
Parameters
element
[in] pointer to the list element.
Return Value
List element index, or -1.
Example:
//--- example for CList::IndexOf(CObject*)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
CObject *object=new CObject;
if(object==NULL)
{
printf("Element create error");
delete list;
return;
}
if(list.Add(object))
{
int pos=list.IndexOf(object);
}
//--- delete list
delete list;
}
2141
Standard Library
GetNodeAtIndex
Gets an element from the specified position in the list.
CObject* GetNodeAtIndex(
int pos
// position
Parameters
pos
[in] element position in the list.
Return Value
pointer to the element - success, NULL - cannot receive a pointer.
Example:
//--- example for CList::GetNodeAtIndex(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetNodeAtIndex(10);
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2142
Standard Library
GetFirstNode
Gets the first element of the list.
CObject* GetFirstNode()
Return Value
Pointer to the first element - success, NULL - cannot get a pointer.
Example:
//--- example for CList::GetFirstNode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetFirstNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2143
Standard Library
GetPrevNode
Gets the previous element of the list.
CObject* GetPrevNode()
Return Value
Pointer to the previous element - successful, NULL - cannot get a pointer.
Example:
//--- example for CList::GetPrevNode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetPrevNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2144
Standard Library
GetCurrentNode
Gets the current list element.
CObject* GetCurrentNode()
Return Value
Pointer to the current element - successful, NULL - cannot get a pointer.
Example:
//--- example for CList::GetCurrentNode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetCurrentNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2145
Standard Library
GetNextNode
Gets the next element in the list.
CObject* GetNextNode()
Return Value
Pointer to the next element - successful, NULL - cannot get a pointer.
Example:
//--- example for CList::GetNextNode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetNextNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2146
Standard Library
GetLastNode
Gets the last element of the list.
CObject* GetLastNode()
Return Value
Pointer to the last element - success, NULL - cannot get a pointer.
Example:
//--- example for CList::GetLastNode()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetLastNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}
2147
Standard Library
Sort
Sorts a list.
void Sort(
int mode
// sorting mode
Parameters
mode
[in] Sorting mode.
Return Value
No.
Note
The list is always sorted in ascending order.
Example:
//--- example for CList::Sort(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- sorting by mode 0
list.Sort(0);
//--- use list
//--- ...
//--- delete list
delete list;
}
2148
Standard Library
MoveToIndex
Moves the current element in the list to the specified position.
bool MoveToIndex(
int pos
// position
Parameters
pos
[in] position in the list to move.
Return Value
true - successful, false - cannot move the element.
Example:
//--- example for CList::MoveToIndex(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- move current node to begin
list.MoveToIndex(0);
//--- use list
//--- . . .
//--- delete list
delete list;
}
2149
Standard Library
Exchange
Swaps two elements in the list.
bool Exchange(
CObject* node1,
// list element
CObject* node2
// list element
Parameters
node1
[in] list element
node2
[in] list element
Return Value
true - successful, false - cannot swap the elements.
Example:
//--- example for CList::Exchange(CObject*,CObject*)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- exchange
list.Exchange(list.GetFirstNode(),list.GetLastNode());
//--- use list
//--- . . .
//--- delete list
delete list;
}
2150
Standard Library
CompareList
Compares the list with another one.
bool CompareList(
CList* list
Parameters
list
[in] a pointer to an instance of the CList class used as a source of elements for comparison.
Return Value
true - the lists are equal, false - the lists are not equal.
Example:
//--- example for CList::CompareList(const CList*)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- create source list
CList *src=new CList;
if(src==NULL)
{
printf("Object create error");
delete list;
return;
}
//--- fill source list
//--- . . .
//--- compare with another list
bool result=list.CompareList(src);
//--- delete lists
delete src;
delete list;
}
2151
Standard Library
Search
Searches for an element equal to the sample in the sorted list.
CObject* Search(
CObject* element
// sample
Parameters
element
[in] element sample to search for in the list.
Return Value
Pointer to the found element - successful, NULL - the element is not found.
Example:
//--- example for CList::Search(CObject*)
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- add lists elements
//--- . . .
//--- sort list
list.Sort(0);
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete list;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(list.Search(sample)!=NULL) printf("Element found");
else
2152
Standard Library
Save
Saves list data in the file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen () function.
Return Value
true - successfully completed, false - error.
Example:
//--- example for CList::Save(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
int
file_handle;
2153
Standard Library
}
2154
Standard Library
Load
Loads list data from the file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] Handle of the binary file previously opened using the FileOpen () function.
Return Value
true - successfully completed, false - error.
Note
When reading list elements from the file, the CList::CreateElement(int) method is called to create
each element.
Example:
//--- example for CLoad::Load(int)
#include <Arrays\List.mqh>
//--void OnStart()
{
int
file_handle;
2155
Standard Library
//--- use list elements
//--- . . .
//--- delete list
delete list;
}
2156
Standard Library
Type
Gets the list type identifier.
virtual int Type()
Return Value
List type identifier (for CList - 7779).
Example:
//--- example for CList::Type()
#include <Arrays\List.mqh>
//--void OnStart()
{
CList *list=new CList;
//--if(list==NULL)
{
printf("Object create error");
return;
}
//--- get list type
int type=list.Type();
//--- delete list
delete list;
}
2157
Standard Library
CTreeNode
CTreeNode is a class of the CTree binary tree node.
Description
CTreeNode provides the ability to work with nodes of the CTree binary tree. Options of navigation
through the tree are implemented in the class. Besides, methods of working with the file are
implemented.
Declaration
class CTreeNode : public CObject
Title
#include <Arrays\TreeNode.mqh>
Left
Right
Balance
BalanceL
BalanceR
Comparison
RefreshBalance
Search
GetNext
Input/Output
SaveNode
LoadNode
virtual Type
Derived classes:
2158
Standard Library
CTree
MyTreeNode.mq5 |
//|
//|
http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
//--#include <Arrays\TreeNode.mqh>
//+------------------------------------------------------------------+
//| Describe CMyTreeNode class derived from CTreeNode.
//+------------------------------------------------------------------+
//| Class CMyTreeNode.
//|
//+------------------------------------------------------------------+
class CMyTreeNode : public CTreeNode
{
protected:
//--- user's data
long
m_long;
double
m_double;
string
m_string;
datetime
m_datetime;
public:
CMyTreeNode();
//--- methods of accessing 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;
Save(int file_handle);
virtual bool
Load(int file_handle);
}
}
}
2159
Standard Library
protected:
virtual int
//| INPUT:
none.
//+------------------------------------------------------------------+
void CMyTreeNode::CMyTreeNode()
{
//--- initialization of user's data
m_long
=0;
m_double
=0.0;
m_string
="";
m_datetime
=0;
}
//+------------------------------------------------------------------+
//| Comparison with another tree node by the specified algorithm.
//| INPUT:
//|
//+------------------------------------------------------------------+
int CMyTreeNode::Compare(const CObject *node,int mode)
{
//--- mode parameter 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.
//+------------------------------------------------------------------+
CTreeNode* CMyTreeNode::CreateSample()
{
CMyTreeNode *result=new CMyTreeNode;
//--return(result);
}
//+------------------------------------------------------------------+
2160
Standard Library
//| Write tree node data to a file.
//| INPUT:
//+------------------------------------------------------------------+
bool CMyTreeNode::Save(int file_handle)
{
uint i=0,len;
//--- checks
if(file_handle<0) return(false);
//--- writing user data
//--- writing custom variable of long type
if(FileWriteLong(file_handle,m_long)!=sizeof(long))
return(false);
return(false);
return(false);
return(false);
//--return(true);
}
//+------------------------------------------------------------------+
//| Read tree node data from a file.
//| INPUT:
//+------------------------------------------------------------------+
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 char type
//--- reading custom variable of long type
m_long=FileReadLong(file_handle);
//--- reading custom variable of double type
m_double=FileReadDouble(file_handle);
//--- reading custom variable of string type
//--- read the string length
len=FileReadInteger(file_handle,INT_VALUE);
//--- read the string
if(len!=0) m_string=FileReadString(file_handle,len);
2161
Standard Library
else
m_string="";
2162
Standard Library
Owner
Gets the pointer of the owner node.
CTreeNode* Owner()
Return Value
Pointer of the owner node.
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.
2163
Standard Library
Left
Gets the pointer of the left node.
CTreeNode* Left()
Return Value
Pointer of the left node.
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.
2164
Standard Library
Right
Gets the pointer of the right node.
CTreeNode* Right()
Return Value
The pointer of the right node.
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.
2165
Standard Library
Balance
Gets the node balance.
int Balance() const
Return Value
Node balance.
2166
Standard Library
BalanceL
Gets the balance of the left sub-branch of the node.
int BalanceL() const
Return Value
Balance of the left sub-branch of the node.
2167
Standard Library
BalanceR
Gets the balance of the right sub-branch of the node.
int BalanceR() const
Return Value
Balance of the right sub-branch of the node.
2168
Standard Library
CreateSample
Creates a new node sample.
virtual CTreeNode* CreateSample()
Return Value
Pointer to the new node sample or NULL.
2169
Standard Library
RefreshBalance
Recalculates the node balance.
int RefreshBalance()
Return Value
Node balance.
2170
Standard Library
GetNext
Gets the pointer of the next node.
CTreeNode* GetNext(
CTreeNode* node
// node
Parameters
node
[in] Node of the search start.
Return Value
Pointer of the next node.
2171
Standard Library
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
true - success, otherwise false.
2172
Standard Library
LoadNode
Reads node data from a file.
bool LoadNode(
int
file_handle,
CTreeNode* main
// handle
// node
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for reading.
main
[in] Node for data.
Return Value
true - success, otherwise false.
2173
Standard Library
Type
Gets the identifier of the node type.
virtual int Type() const
Return Value
Identifier of the node type.
2174
Standard Library
CTree
CTree is a class of the binary tree of the instances of CTreeNode class and its descendants.
Description
CTree class provides the possibility to work with the binary tree of CTreeNode class instances and its
descendants. Options of adding/inserting/deleting of tree elements and search in the tree are
implemented in the class. Besides that, methods of working with a file are implemented.
Note that mechanism of dynamic memory management is not implemented in class CTree (unlike
classes CList and CArrayObj). All tree nodes are deleted with memory deallocation.
Declaration
class CTree : public CTreeNode
Title
#include <Arrays\Tree.mqh>
Filling
Insert
Deletion
Detach
Delete
Clear
Search
Find
Input/output
virtual Save
virtual Load
virtual Type
Trees of CTreeNode class descendants descendants of class CTree - have practical application.
2175
Standard Library
Descendant of CTree class should have a predefined method CreateElement that creates a new
instance of the CTreeNode descendant class.
Let's consider an example of the CTree descendant class.
//+------------------------------------------------------------------+
//|
MyTree.mq5 |
//|
//|
http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link
"https://www.mql5.com"
//--#include <Arrays\Tree.mqh>
#include "MyTreeNode.mqh"
//--input int extCountedNodes = 100;
//+------------------------------------------------------------------+
//| Describe class CMyTree derived from CTree.
//+------------------------------------------------------------------+
//| Class CMyTree.
//+------------------------------------------------------------------+
class CMyTree : public CTree
{
public:
//--- methods of searching in the tree by custom data
CMyTreeNode*
FindByLong(long find_long);
//| INPUT:
none.
//+------------------------------------------------------------------+
CTreeNode *CMyTree::CreateElement()
{
CMyTreeNode *node=new CMyTreeNode;
//--return(node);
}
//+------------------------------------------------------------------+
//| Search of element in a list by value m_long.
//| INPUT:
2176
Standard Library
//| REMARK: none.
//+------------------------------------------------------------------+
CMyTreeNode* CMyTree::FindByLong(long find_long)
{
CMyTreeNode *res=NULL;
CMyTreeNode *node;
//--- create a tree node to pass the search parameter
node=new CMyTreeNode;
if(node==NULL) return(NULL);
node.SetLong(find_long);
//--res=Find(node);
delete node;
//--return(res);
}
//+------------------------------------------------------------------+
//| script "testing of class CMyTree"
//+------------------------------------------------------------------+
//---
string str_array[11]={"p","oo","iii","uuuu","yyyyy","ttttt","rrrr","eee","ww","q","999"};
//--int OnStart() export
{
int
i;
uint
pos;
int
beg_time,end_time;
2177
Standard Library
//--- 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();
2178
Standard Library
//--MyTree.Clear();
TmpMyTree.Clear();
//--printf("End test %s. OK!",__FILE__);
//--return(0);
}
//+------------------------------------------------------------------+
//| Function to output node contents to journal
//+------------------------------------------------------------------+
void NodeToLog(CMyTreeNode *node)
{
printf("
%I64d,%f,'%s','%s'",
node.GetLong(),node.GetDouble(),
node.GetString(),TimeToString(node.GetDateTime()));
}
//+------------------------------------------------------------------+
//| Function to populate 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);
}
2179
Standard Library
Root
Gets the root node of the tree.
CTreeNode* Root() const
Return Value
Pointer of the root node of the tree.
2180
Standard Library
CreateElement
Creates a new instance of the node.
virtual CTreeNode* CreateElement()
Return Value
Pointer of the new instance of the node or NULL.
2181
Standard Library
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
Pointer of the owner node or NULL.
2182
Standard Library
Detach
Detaches a specified node from a tree.
bool Detach(
CTreeNode* node
// node
Parameters
node
[in] Node pointer to detach.
Return Value
true - success, otherwise false.
Note
After detachment, the node pointer is not released. The tree is balanced.
2183
Standard Library
Delete
Deletes a specified node from a tree.
bool Delete(
CTreeNode* node
// node
Parameters
node
[in] Node pointer to delete.
Return Value
true - success, otherwise false.
Note
After deletion, a node pointer is released. The tree is balanced.
2184
Standard Library
Clear
Deletes all nodes of a tree.
void Clear()
Return Value
None.
Note
After deletion, node pointers are released.
2185
Standard Library
Find
Searches for a node in a tree by sample.
CTreeNode* Find(
CTreeNode* node
// node
Parameters
node
[in] Node that contains data used as a search sample.
Return Value
Pointer of the found node or NULL.
2186
Standard Library
Save
Writes tree data to a file.
virtual bool Save(
int file_handle
// handle
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for writing.
Return Value
true - success, otherwise false.
2187
Standard Library
Load
Reads tree data from a file.
virtual bool Load(
int file_handle
// handle
Parameters
file_handle
[in] Handle of a binary file that was earlier opened for reading.
Return Value
true - success, otherwise false.
2188
Standard Library
Type
Gets identifier of the tree type.
virtual int Type() const
Return Value
Identifier of the tree type.
2189
Standard Library
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 located in the working directory of the
terminal in the Include\ChartObjects folder.
Class/Group
Description
Lines
Channels
Gann Tools
Fibonacci Tools
Elliott Tools
Shapes
Arrows
Controls
2190
Standard Library
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
ChartId
Window
Name
NumPoints
Assign
Attach
SetPoint
Delete
Delete
Detach
Shift
ShiftObject
ShiftPoint
Object properties
Time
Price
Color
Style
2191
Standard Library
Width
BackGround
Selected
Selectable
Description
Tooltip
Timeframes
Z_Order
CreateTime
LevelColor
LevelStyle
LevelWidth
LevelValue
LevelDescription
SetInteger
GetDouble
SetDouble
GetString
SetString
Input/Output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectArrow
CChartObjectBitmap
CChartObjectBmpLabel
CChartObjectCycles
2192
Standard Library
CChartObjectElliottWave3
CChartObjectEllipse
CChartObjectFiboArc
CChartObjectFiboFan
CChartObjectFiboTimes
CChartObjectHLine
CChartObjectRectangle
CChartObjectSubChart
CChartObjectText
CChartObjectTrend
CChartObjectTriangle
CChartObjectVLine
2193
Standard Library
ChartId
Gets the ID of the chart a graphic object belongs to.
long ChartId() const
Return Value
Id chart on which the graphic object is located. If object not found, it returns -1.
Example:
//--- example for CChartObject::ChartId
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get chart idintifier of chart object
long chart_id=object.ChartId();
}
2194
Standard Library
Window
Gets the chart window index on which the graphic object is located.
int Window() const
Return Value
Chart window number where the graphic object is located (0 - main window). If object not found, it
returns -1.
Example:
//--- example for CChartObject::Window
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get window of chart object
int window=object.Window();
}
2195
Standard Library
Return Value
Name of the graphic object attached to an instance of the class. If object not found, returns NULL.
// new name
Parameters
name
[in] The new name of the graphic object.
Return Value
true if successful, false - if you can not change the name.
Example:
//--- example for CChartObject::Name
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get name of chart object
string object_name=object.Name();
if(object_name!="MyChartObject")
{
//--- set name of chart object
object.Name("MyChartObject");
}
}
2196
Standard Library
NumPoints
Gets the number of anchor points of a graphic object.
int NumPoints() const
Return Value
Number of points linking a graphic object attached to an instance of the class. If no attached object,
it returns 0.
Example:
//--- example for CChartObject::NumPoints
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get points count of chart object
int points=object.NumPoints();
}
2197
Standard Library
Attach
Attaches a graphical object to an instance of the class.
bool Attach(
long
chart_id,
// Chart ID
string name,
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 anchor points of the graphic object.
Return Value
true - if successful, false - if operation has failed.
Example:
//--- example for CChartObject::Attach
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- attach chart object
if(!object.Attach(ChartID(),"MyObject",0,2))
{
printf("Object attach error");
return;
}
}
2198
Standard Library
SetPoint
Sets new coordinates of this anchor point of the graphic object.
bool SetPoint(
int
point,
// Point number
datetime new_time,
// Time coordinate
double
// Price coordinate
new_price
Parameters
point
[in] Number of an anchor point.
new_time
[in] New value for the time coordinate of the specified anchor point.
new_price
[in] New value for price coordinate of the specified anchor point.
Return Value
true - if successful, false - if you can not change coordinates of the point.
Example:
//--- example for CChartObject::SetPoint
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
double
price;
//--if(object.NumPoints()>0)
{
//--- set point of chart object
object.SetPoint(0,CurrTime(),price);
}
}
2199
Standard Library
Delete
Removes an attached graphical object from the chart.
bool Delete()
Return Value
true - if successful, false - if removal has failed.
Example:
//--- example for CChartObject::Delete
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- detach chart object
if(!object.Delete())
{
printf("Object delete error");
return;
}
}
2200
Standard Library
Detach
Detaches the graphic object.
void Detach()
Return Value
None.
Example:
//--- example for CChartObject::Detach
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- detach chart object
object.Detach();
}
2201
Standard Library
ShiftObject
Moves a graphic object.
bool ShiftObject(
datetime d_time,
double
d_price
Parameters
d_time
[in] Increment of the time coordinate for all anchor points.
d_price
[in] Increment of the price coordinate for all anchor points.
Return Value
true - if successful, false - if you can not shift the object.
Example:
//--- example for CChartObject::ShiftObject
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
datetime
d_time;
double
d_price;
2202
Standard Library
ShiftPoint
Shifts a specified anchor point of the graphic object.
bool ShiftPoint(
int
point,
// Point number
datetime d_time,
double
d_price
Parameters
point
[in] Number of an anchor point.
d_time
[in] Increment of the time coordinate for the specified point.
d_price
[in] Increment of the price coordinate for the specified point.
Return Value
true - if successful, false - if you can not shift the point.
Example:
//--- example for CChartObject::ShiftPoint
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
datetime
d_time;
double
d_price;
//--if(object.NumPoints()>0)
{
//--- shift point of chart object
object.ShiftPoint(0,d_time,d_price);
}
}
2203
Standard Library
// Point number
) const
Parameters
point
[in] Number of an anchor point.
Return Value
Time coordinate of the specified anchor point of the graphic object attached to an instance of the
class. If there is no attached object or the object does not have this point, it returns 0.
point,
datetime new_time
// Point number
// Time
Parameters
point
[in] Number of an anchor point.
new_time
[in] New value for the time coordinate of the specified anchor point.
Return Value
true - if successful, false - if you can not change the time coordinate.
Example:
//--- example for CChartObject::Time
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.NumPoints();i++)
{
//--- get time of the chart object point
datetime point_time=object.Time(i);
if(point_time==0)
2204
Standard Library
{
//--- set time of the chart object point
object.Time(i,TimeCurrent());
}
}
}
2205
Standard Library
// Point number
) const
Parameters
point
[in] Number of an anchor point.
Return Value
Price coordinate of the specified anchor point of the graphic object attached to an instance of the
class. If there is no attached object or the object does not have this point, it returns EMPTY_VALUE.
point,
double new_price
// Point number
// Price
Parameters
point
[in] Number of an anchor point.
new_price
[in] New value for the price coordinate of the specified anchor point.
Return Value
true - if successful, false - if you can not change the price coordinate.
Example:
//--- example for CChartObject::Price
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
double
price;
//--for(int i=0;i<object.NumPoints();i++)
{
//--- get price of the chart object point
double point_price=object.Price(i);
2206
Standard Library
if(point_price!=price)
{
//--- set price for the chart object point
object.Price(i,price);
}
}
}
2207
Standard Library
Return Value
Line color of the graphic object attached to the class instance. If there is no object attached, it
returns CLR_NONE.
// New color
Parameters
new_color
[in] New value of line color.
Return Value
true - if successful, false - if you can not change the color.
Example:
//--- example for CChartObject::Color
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get color of chart object
color object_color=object.Color();
if(object_color!=clrRed)
{
//--- set color of chart object
object.Color(clrRed);
}
}
2208
Standard Library
Return Value
Line style of the graphic object attached to the class instance. If there is no attached object, it
returns WRONG_VALUE.
// Style
Parameters
new_style
[in] New value of the line style.
Return Value
true - if successful, false - if you can not change the style.
Example:
//--- example for CChartObject::Style
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get style of chart object
ENUM_LINE_STYLE style=object.Style();
if(style!=STYLE_SOLID)
{
//--- set style of chart object
object.Style(STYLE_SOLID);
}
}
2209
Standard Library
Return Value
The line width of the graphic object attached to an instance of the class. If there is no attached
object, it returns -1.
// Thickness
Parameters
new_width
[in] New value of the line width.
Return Value
true - if successful, false - if you can not change the width.
Example:
//--- example for CChartObject::Width
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get width of chart object
int width=object.Width();
if(width!=1)
{
//--- set width of chart object
object.Width(1);
}
}
2210
Standard Library
Return Value
Flag for drawing the graphic object, attached to an instance of the class, on the background. If
there is no attached object, returns false.
Parameters
background
[in] New value of the flag for drawing a graphic object on the background.
Return Value
true - if successful, false - if you can not change the flag.
Example:
//--- example for CChartObject::Background
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get background flag of chart object
bool background_flag=object.Background();
if(!background_flag)
{
//--- set background flag of chart object
object.Background(true);
}
}
2211
Standard Library
Return Value
The state that the object, attached to an instance of the class, is selected. If there is no attached
object, returns false.
Parameters
selected
[in] New value of the flag.
Return Value
true - if successful, false - if you can not change the flag.
Example:
//--- example for CChartObject::Selected
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get the "selected" flag of chart object
bool selected_flag=object.Selected();
if(selected_flag)
{
//--- set the "selected" flag of chart object
object.Selected(false);
}
}
2212
Standard Library
Return Value
Flag indicating the ability of the object, attached to an instance of the class, to be selected. If there
is no attached object, returns false.
Parameters
selectable
[in] New value of the flag.
Return Value
true - if successful, false - if you can not change the flag.
Example:
//--- example for CChartObject::Selectable
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get the "selectable" flag of chart object
bool selectable_flag=object.Selectable();
if(selectable_flag)
{
//--- set the "selectable" flag of chart object
object.Selectable(false);
}
}
2213
Standard Library
Return Value
Description (text) of the graphic object attached to an instance of the class. If there is no attached
object, it returns NULL.
// Text
Parameters
text
[in] New description (text).
Return Value
true - if successful, false - if you can not change the description (text).
Example:
//--- example for CChartObject::Description
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get description of chart object
string description=object.Description();
if(description=="")
{
//--- set description of chart object
object.Description("MyObject");
}
}
2214
Standard Library
Return Value
The text of a tooltip of the graphic object attached to an instance of the class. If there is no
attached object, it returns NULL.
Parameters
new_tooltip
[in] New text of a tooltip.
Return Value
true if successful, false if tooltip change has failed.
Note:
If the property is not set, then the tooltip generated automatically by the terminal is shown. A
tooltip can be disabled by setting the "\n" (line feed) value.
2215
Standard Library
Return Value
Visibility flags of the graphic object attached to an instance of the class. If there is no attached
object, it returns 0.
// Visibility flags
Parameters
new_timeframes
[in] New visibility flags of the graphic object.
Return Value
true - if successful, false - if you can not change the flags of visibility.
Example:
//--- example for CChartObject::Timeframes
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get timeframes of chart object
int timeframes=object.Timeframes();
if(!(timeframes&OBJ_PERIOD_H1))
{
//--- set timeframes of chart object
object.Timeframes(timeframes|OBJ_PERIOD_H1);
}
}
2216
Standard Library
Return Value
Priority of a graphic object, attached to the class instance. If there is no object attached, it returns
0.
// new priority
Parameters
value
[in] New value of priority of a graphical object of clicking on the chart (CHARTEVENT_CLICK).
Return Value
true - if successful, false - if you can not change the priority.
Note
Z_Order is a priority of a graphical object for receiving events of clicking on a chart
(CHARTEVENT_CLICK). By setting the value greater than 0(default value) you can increase the object
priority.
2217
Standard Library
CreateTime
Gets the create time of a graphical object.
datetime CreateTime() const
Return Value
Creation time of the graphical object attached to the instance of the class. If there is no attached
object, it returns 0.
Example:
//--- example for CChartObject::CreateTime
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get create time of chart object
datetime create_time=object.CreateTime();
}
2218
Standard Library
Return Value
Number of levels of the graphical object attached to an instance of the class. If there is no attached
object, it returns 0.
// Number of levels
Parameters
levels
[in] The new number of levels of the graphic object.
Return Value
true - if successful, false - if you can not change the number of levels.
Example:
//--- example for CChartObject::LevelsCount
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get levels count of chart object
int levels_count=object.LevelsCount();
//--- set levels count of chart object
object.LevelsCount(levels_count+1);
}
2219
Standard Library
// Level number
) const
Parameters
level
[in] Number of level.
Return Value
Line color of the specified level of the graphic object attached to the instance of the class. If there
is no attached object or the object does not have the specified level, it returns CLR_NONE.
level,
color new_color
// Level number
// New color
Parameters
level
[in] Number of level.
new_color
[in] New line color of the specified level.
Return Value
true - if successful, false - if you can not change the color.
Example:
//--- example for CChartObject::LevelColor
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.LevelsCount();i++)
{
//--- get level color of chart object
color level_color=object.LevelColor(i);
if(level_color!=clrRed)
2220
Standard Library
{
//--- set level color of chart object
object.LevelColor(i,clrRed);
}
}
}
2221
Standard Library
// Level number
) const
Parameters
level
[in] Number of level.
Return Value
Line style of the specified level of the graphical object attached to an instance of the class. If there
is no attached object or the object does not have the specified level, it returns WRONG_VALUE.
level,
ENUM_LINE_STYLE style
// Level number
// Line Style
Parameters
level
[in] Number of level.
style
[in] New line style of the specified level.
Return Value
true - if successful, false - if you can not change the style.
Example:
//--- example for CChartObject::LevelStyle
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.LevelsCount();i++)
{
//--- get level style of chart object
ENUM_LINE_STYLE level_style=object.LevelStyle(i);
if(level_style!=STYLE_SOLID)
2222
Standard Library
{
//--- set level style of chart object
object.LevelStyle(i,STYLE_SOLID);
}
}
}
2223
Standard Library
// Level number
) const
Parameters
level
[in] Number of level.
Return Value
Line width of the specified level of the graphical object attached to the instance of the class. If
there is no attached object or the object does not have the specified level, it returns -1.
// Level number
int new_width
// New width
Parameters
level
[in] Number of level.
new_width
[in] New line width of the specified level.
Return Value
true - if successful, false - if you can not change the width.
Example:
//--- example for CChartObject::LevelWidth
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.LevelsCount();i++)
{
//--- get level width of chart object
int level_width=object.LevelWidth(i);
if(level_width!=1)
2224
Standard Library
{
//--- set level width of chart object
object.LevelWidth(i,1);
}
}
}
2225
Standard Library
// Level number
) const
Parameters
level
[in] Number of level.
Return Value
The value of this level of graphical object that is bound to an instance of the class. If there is no
bound object or the object has no level specified, returns EMPTY_VALUE.
level,
double new_value
// Level number
// New value
Parameters
level
[in] Number of level.
new_value
[in] New value of the specified level.
Return Value
true - if successful, false - if you can not change the value.
Example:
//--- example for CChartObject::LevelValue
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.LevelsCount();i++)
{
//--- get level value of chart object
double level_value=object.LevelValue(i);
if(level_value!=0.1*i)
2226
Standard Library
{
//--- set level value of chart object
object.LevelValue(i,0.1*i);
}
}
}
2227
Standard Library
// 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. Returns
NULL if there is no bound object or the object has no specified level.
level ,
string text
// Level number
// 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:
//--- example for CChartObject::LevelDescription
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--for(int i=0;i<object.LevelsCount();i++)
{
//--- get level description of chart object
string level_description=object.LevelDescription(i);
if(level_description=="")
2228
Standard Library
{
//--- set level description of chart object
object.LevelDescription(i,"Level_"+IntegerToString(i));
}
}
}
2229
Standard Library
GetInteger
Provides simplified access to the functions of API MQL5 ObjectGetInteger() for properties with integer
values (of type bool, char, uchar, short, ushort, int, uint, long, ulong, datetime, color) bound to an
instance of the class graphic. There are two versions of a function call:
Getting a property value without checking the correctness
long GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id,
// Identifier of integer-property
int
// Modifier
modifier=-1
) const
Parameters
prop_id
[in] ID of integer-graphic properties.
modifier=-1
[in] Modifier (index) integer-features.
Return Value
If successfull, it returns the value of integer-type property, if error, it returns 0.
Getting a property value in verifying the correctness of such treatment
bool GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id,
// Identifier of integer-property
int
modifier,
// Modifier
long&
value
// Link to variable
) 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
true - if successful, false - if you can not get integer-property.
Example:
//--- example for CChartObject::GetInteger
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
2230
Standard Library
{
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);
}
}
2231
Standard Library
SetInteger
Provides simplified access to the functions of API MQL5 ObjectSetInteger() to change properties with
integer values (with types bool, char, uchar, short, ushort, int, uint, long, ulong, datetime, color)
bound to an instance of the class graphic.There are two versions of a function call:
Setting a property value that does not require a modifier
bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id,
// Identifier of integer-property
long
// Value
value
Parameters
prop_id
[in] ID integer-graphic properties of the object.
value
[in] New value of mutable integer property.
Setting a property value indicating the modifier
bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id,
// Identifier of integer-property
int
modifier,
// Modifier
long
value
// Value
Parameters
prop_id
[in] ID integer-graphic properties of the object.
modifier
[in] Modifier (index) integer-property.
value
[in] new mutable integer-value properties.
Return Value
true - if successful, false - if you can not change the integer-property.
Example:
//--- example for CChartObject::SetInteger
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- set new color of chart object
2232
Standard Library
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;
}
}
}
2233
Standard Library
GetDouble
Provides simplified access to the functions of API MQL5 ObjectGetDouble() to get properties with
double values (having type float and double) of the graphic object, assigned to the class instance.
There are two versions of a function call:
Getting a property value without checking the correctness
double GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id,
// Identifier of double-property
int
// Modifier
modifier=-1
) 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.
Getting a property value in verifying the correctness of such treatment
bool GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id,
// Identifier of double-property
int
modifier,
// Modifier
double&
value
// Link to variable
) 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
true - if successful, false - if you can not get a double-feature.
Example:
//--- example for CChartObject::GetDouble
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
2234
Standard Library
{
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);
}
}
2235
Standard Library
SetDouble
Provides simplified access to the functions of API MQL5 ObjectSetDouble() to change properties with
double values (having type float and double) bound to an instance of the class graphic object. There
are two versions of a function call:
Setting a property value that does not require a modifier
bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id,
// Identifier of double-property
double
// Value
value
Parameters
prop_id
[in] ID of double-graphic properties.
value
[in] New value of mutable double property.
Setting a property value indicating the modifier
bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id,
// Identifier of double-property
int
modifier,
// Modifier
double
value
// Value
Parameters
prop_id
[in] ID of double-graphic properties.
modifier
[in] Modifier (index) of double-property.
value
[in] New value mutable double-property.
Return Value
true - if successful, false - if you can not change the double-feature.
Example:
//--- example for CChartObject::SetDouble
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//---
2236
Standard Library
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;
}
}
}
2237
Standard Library
GetString
Provides simplified access to the functions of API MQL5 ObjectGetString() for properties with string
values bound to an instance of the class graphic object. There are two versions of a function call:
Getting a property value without checking the correctness
string GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id,
// Identifier of string-property
int
// Modifier
modifier=-1
) const
Parameters
prop_id
[in] Identifier string-properties of graphic object.
modifier=-1
[in] Modifier (index) string-properties.
Return Value
Value of string-property.
Getting a property value in verifying the correctness of such treatment
bool GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id,
// Identifier of string-property
int
modifier,
// Modifier
string&
value
// Link to variable
) 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
true - if successful, false - if you can not get a string-property.
Example:
//--- example for CChartObject::GetString
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
2238
Standard Library
CChartObject object;
string
value;
2239
Standard Library
SetString
Provides simplified access to the functions of API MQL5 ObjectSetString() to change properties with
string values bound to an instance of the class graphic object. There are two versions of a function
call:
Setting a property value that does not require a modifier
bool 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 of mutable string property.
Setting a property value indicating the modifier
bool SetString(
ENUM_OBJECT_PROPERTY_STRING prop_id,
// Identifier of string-property
int
modifier,
// Modifier
string
value
// Value
Parameters
prop_id
[in] Identifier string-properties of graphic object.
modifier
[in] Modifier (index) string-properties.
value
[in] New value mutable string-properties.
Return Value
true - if successful, false - if you can not change the string-property.
Example:
//--- example for CChartObject::SetString
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- set new name of chart object
2240
Standard Library
if(!object.SetString(OBJPROP_NAME,"MyObject"))
{
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;
}
}
}
2241
Standard Library
Save
Saves parameters of the object in the file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] Handle of the file previously opened using the function FileOpen (...).
Return Value
true - if successfully completed, false - if an error.
Example:
//--- example for CChartObject::Save
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
int
file_handle;
2242
Standard Library
Load
Loads the parameters of the object from the file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the file previously opened using the function FileOpen (...).
Return Value
true - if successfully completed, false - if an error.
Example:
//--- example for CChartObject::Load
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
int
file_handle;
CChartObject object;
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!object.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
FileClose(file_handle);
//--return;
}
FileClose(file_handle);
}
//--- use object
//--- . . .
}
2243
Standard Library
Type
Gets the type identifier of a graphic object.
virtual int Type() const
Return Value
Object type identifier (0x8888 for CChartObject).
Example:
//--- example for CChartObject::Type
#include <ChartObjects\ChartObject.mqh>
//--void OnStart()
{
CChartObject object;
//--- get object type
int type=object.Type();
}
2244
Standard Library
Line Objects
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 .
Class name
Object
CChartObjectVLine
CChartObjectHLine
CChartObjectTrend
CChartObjectTrendByAngle
CChartObjectCycles
See also
Object types, Graphic objects
2245
Standard Library
CChartObjectVLine
Class CChartObjectVLine is a class for simplified access to "Vertical Line" graphic object properties.
Description
Class CChartObjectVLine provides access to "Vertical Line" object properties.
Declaration
class CChartObjectVLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2246
Standard Library
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] a unique name of the object to create.
window
[in] Chart window number (0 base window).
time
[in] Time coordinate of the anchor point.
Return Value
true if successful, false if error.
2247
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_VLINE for CChartObjectVLine).
2248
Standard Library
CChartObjectHLine
Class CChartObjectHLine is a class for simplified access to "Horizontal Line" graphic object properties.
Description
Class CChartObjectHLine provides access to "Horizonal Line" object properties.
Declaration
class CChartObjectHLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2249
Standard Library
Create
Creates graphic object "Horizontal Line".
bool Create(
long
chart_id,
// Chart identifier
string name,
// Object name
long
// Chart window
window,
double price
// Price 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).
price
[in] Price coordinate of the anchor point.
Return Value
true if successful, false if error.
2250
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_HLINE for CChartObjectHLine).
2251
Standard Library
CChartObjectTrend
Class CChartObjectTrend is a class for simplified access to "Trend Line" graphic object properties.
Description
Class CChartObjectTrend provides access to "Trend Line" object properties.
Declaration
class CChartObjectTrend : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Create
Properties
RayLeft
RayRight
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectChannel
CChartObjectFibo
CChartObjectFiboChannel
CChartObjectFiboExpansion
CChartObjectGannFan
CChartObjectGannGrid
CChartObjectPitchfork
CChartObjectRegression
CChartObjectStdDevChannel
CChartObjectTrendByAngle
See also
Object types, Graphic objects
2252
Standard Library
Create
Creates graphic object "Trend Line".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2253
Standard Library
Return Value
The value of "Ray Left" property, assigned to the class instance. If there is no object assigned, it
returns false.
// flag
Parameters
ray
[in] New value of the "Ray Left" property.
Return Value
true if successful, false if flag hasn't changed error.
2254
Standard Library
Return Value
The value of "Ray Right" property, assigned to the class instance. If there is no object assigned, it
returns false.
// flag
Parameters
ray
[in] New value of the "Ray Right" property.
Return Value
true if successful, false if flag hasn't changed error.
2255
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, false if error.
2256
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, false if error.
2257
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_TREND for CChartObjectTrend).
2258
Standard Library
CChartObjectTrendByAngle
Class CChartObjectTrendByAngle is a class for simplified access to "Trend Line by Angle" graphic
object properties.
Description
Class CChartObjectTrendByAngle provides access to "Trend Line by Angle" object properties.
Declaration
class CChartObjectTrendByAngle : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Create
Properties
Angle
Input/output
virtual Type
Derived classes:
CChartObjectGannLine
See also
Object types, Graphic objects
2259
Standard Library
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,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2260
Standard Library
Return Value
The value of "Angle" property, assigned to the class instance. If there is no object assigned, it
returns EMPTY_VALUE.
// Angle
Parameters
angle
[in] New value of the "Angle" property.
Return Value
true if successful, false if property hasn't changed.
2261
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_TRENDBYANGLE for CChartObjectTrendByAngle).
2262
Standard Library
CChartObjectCycles
Class CChartObjectCycles is a class for simplified access to "Cyclic Lines" graphic object properties.
Description
Class CChartObjectCycles provides access to "Cyclic Lines" object properties.
Declaration
class CChartObjectCycles : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2263
Standard Library
Create
Creates graphic object "Cyclic Lines"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
long
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2264
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_CYCLES for CChartObjectCycles).
2265
Standard Library
Channel Objects
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 .
Class name
Object
CChartObjectChannel
CChartObjectRegression
CChartObjectStdDevChannel
CChartObjectPitchfork
See also
Object types, Graphic objects
2266
Standard Library
CChartObjectChannel
The CChartObjectChannel is a class for simplified access to "Equidistant Channel" graphic object
properties.
Description
The class CChartObjectChannel provides access to "Equidistant Channel" object properties.
Declaration
class CChartObjectChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2267
Standard Library
Create
Creates graphic object "Equidistant Channel"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
Parameters
chart_id
[in] Chart ID (0 current chart).
name
[in] A 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.
Return Value
true if successful, false if error.
2268
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_CHANNEL for CChartObjectChannel).
2269
Standard Library
CChartObjectRegression
Class CChartObjectRegression is a class for simplified access to "Linear Regression Channel" graphic
object properties.
Description
Class CChartObjectRegression provides access to "Linear Regression Channel" object properties.
Declaration
class CChartObjectRegression : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2270
Standard Library
Create
Creates graphic object "Linear Regression Channel"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
long
window,
// Chart window
datetime time1,
datetime time2
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).
time1
[in] Time coordinate of the first anchor point.
time2
[in] Time coordinate of the second anchor point.
Return Value
true if successful, false if error.
2271
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_REGRESSION for CChartObjectRegression).
2272
Standard Library
CChartObjectStdDevChannel
Class CChartObjectStdDevChannel is a class for simplified access to "Standard Deviation Channel"
graphic object properties.
Description
Class CChartObjectStdDevChannel provides access to "Standard Deviation Channel" object properties.
Declaration
class CChartObjectStdDevChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Create
Properties
Deviations
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Graphic objects
2273
Standard Library
Create
Creates graphic object "Standard Deviation Channel"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
datetime time2,
double
// Deviation
deviation
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).
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.
Return Value
true if successful, false if error.
2274
Standard Library
Return Value
Numerical value of "Deviation" property, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
// Deviation
Parameters
deviation
[in] New value for "Deviation" property.
Return Value
true if successful, false if property hasn't changed.
2275
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, false if error.
2276
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, false if error.
2277
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_STDDEVCHANNEL for CChartObjectStdDevChannel).
2278
Standard Library
CChartObjectPitchfork
Class CChartObjectPitchfork is a class for simplified access to "Andrew's Pitchfork" graphic object
properties.
Description
Class CChartObjectPitchfork provides access to "Andrew's Pitchfork" object properties.
Declaration
class CChartObjectPitchfork : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2279
Standard Library
Create
Creates graphic object "Andrew's Pitchfork"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
long
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error.
2280
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_PITCHFORK for CChartObjectPitchfork).
2281
Standard Library
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 .
Class name
Object
CChartObjectGannLine
CChartObjectGannFan
CChartObjectGannGrid
See also
Object types, Graphic objects
2282
Standard Library
CChartObjectGannLine
Class CChartObjectGannLine is a class for simplified access to "Gann Line" graphic object properties.
Description
Class CChartObjectGannLine provides access to "Gann Line" object properties.
Declaration
class CChartObjectGannLine : public CChartObjectTrendByAngle
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Create
Properties
PipsPerBar
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Graphic objects
2283
Standard Library
Create
Creates graphic object "Gann Line".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
ppb
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).
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.
Return Value
true if successful, false if error.
2284
Standard Library
Return 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.
Parameters
ppb
[in] New value for "Pips per bar" property.
Return Value
true if successful, false if property hasn't changed.
2285
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2286
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2287
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_GANNLINE for CChartObjectGannLine).
2288
Standard Library
CChartObjectGannFan
Class CChartObjectGannFan is a class for simplified access to "Gann Fan" graphic object properties.
Description
Class CChartObjectGannFan provides access to "Gann Fan" object properties.
Declaration
class CChartObjectGannFan : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Create
Properties
PipsPerBar
Downtrend
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Graphic objects
2289
Standard Library
Create
Creates graphic object "Gann Fan".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
ppb
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).
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.
Return Value
true if successful, false if error.
2290
Standard Library
Return 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.
Parameters
ppb
[in] New value for "Pips per bar" property.
Return Value
true if successful, false if property hasn't changed.
2291
Standard Library
Return Value
Value of the "Downtrend" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// Flag value
Parameters
downtrend
[in] New value for "Downtrend" property.
Return Value
true if successful, false if property hasn't changed.
2292
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2293
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2294
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_GANNFAN for CChartObjectGannFan).
2295
Standard Library
CChartObjectGannGrid
Class CChartObjectGannGrid is a class for simplified access to "Gann Grid" graphic object properties.
Description
Class CChartObjectGannGrid provides access to "Gann Grid" object properties.
Declaration
class CChartObjectGannGrid : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create
Create
Properties
PipsPerBar
Downtrend
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Graphic objects
2296
Standard Library
Create
Creates graphic object "Gann Grid".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
ppb
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).
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.
Return Value
true if successful, false if error.
2297
Standard Library
Return 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.
Parameters
ppb
[in] New value for "Pips per bar" property.
Return Value
true if successful, false if property hasn't changed.
2298
Standard Library
Return Value
Value of "Downtrend" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// Flag value
Parameters
downtrend
[in] New value for "Downtrend" property.
Return Value
true if successful, false if property hasn't changed.
2299
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2300
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2301
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_GANNGRID for CChartObjectGannGrid).
2302
Standard Library
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 .
Class name
Object
CChartObjectFibo
CChartObjectFiboTimes
CChartObjectFiboFan
CChartObjectFiboArc
CChartObjectFiboChannel
CChartObjectFiboExpansion
See also
Object types, Graphic objects
2303
Standard Library
CChartObjectFibo
Class CChartObjectFibo is a class for simplified access to "Fibonacci Retracement" graphic object
properties.
Description
Class CChartObjectFibo provides access to "Fibonacci Retracement" object properties.
Declaration
class CChartObjectFibo : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2304
Standard Library
Create
Creates graphic object "Fibonacci Retracement".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2305
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_FIBO for CChartObjectFibo).
2306
Standard Library
CChartObjectFiboTimes
Class CChartObjectFiboTimes is a class for simplified access to "Fibonacci Time Zones" graphic object
properties.
Description
Class CChartObjectFiboTimes provides access to "Fibonacci Time Zones" object properties.
Declaration
class CChartObjectFiboTimes : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2307
Standard Library
Create
Creates graphic object "Fibonacci Time Zones".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2308
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_FIBOTIMES for CChartObjectFiboTimes).
2309
Standard Library
CChartObjectFiboFan
Class CChartObjectFiboFan is a class for simplified access to "Fibonacci Fan" graphic object
properties.
Description
Class CChartObjectFiboFan provides access to "Fibonacci Fan" object properties.
Declaration
class CChartObjectFiboFan : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2310
Standard Library
Create
Creates graphic object "Fibonacci Fan".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error.
2311
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_FIBOFAN for CChartObjectFiboFan).
2312
Standard Library
CChartObjectFiboArc
Class CChartObjectFiboArc is a class for simplified access to "Fibonacci Arc" graphic object properties.
Description
Class CChartObjectFiboArc provides access to "Fibonacci Arc" object properties.
Declaration
class CChartObjectFiboArc : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Properties
Scale
Ellipse
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Graphic objects
2313
Standard Library
Create
Creates graphic object "Fibonacci Arc"
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
double
scale
// Scale
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).
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.
Return Value
true if successful, false if error.
2314
Standard Library
Return Value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
// Scale
Parameters
scale
[in] New value for "Scale" property.
Return Value
true if successful, false if property hasn't changed.
2315
Standard Library
Return Value
Value of "Ellipse" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// flag value
Parameters
ellipse
[in] New value for "Scale" property.
Return Value
true if successful, false if property hasn't changed.
2316
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2317
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2318
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_FIBOARC for CChartObjectFiboArc).
2319
Standard Library
CChartObjectFiboChannel
Class CChartObjectFiboChannel is a class for simplified access to "Fibonacci Channel" graphic object
properties.
Description
Class CChartObjectFiboChannel provides access to "Fibonacci Channel" object properties.
Declaration
class CChartObjectFiboChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2320
Standard Library
Create
Creates graphic object "Fibonacci Channel".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error.
2321
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_FIBOCHANNEL for CChartObjectFiboChannel).
2322
Standard Library
CChartObjectFiboExpansion
Class CChartObjectFiboExpansion is a class for simplified access to "Fibonacci Expansion" graphic
object properties.
Description
Class CChartObjectFiboExpansion provides access to "Fibonacci Expansion" object properties.
Declaration
class CChartObjectFiboExpansion : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2323
Standard Library
Create
Creates graphic object "Fibonacci Expansion".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error.
2324
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_EXPANSION for CChartObjectFiboExpansion).
2325
Standard Library
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 .
Class name
Object
CChartObjectElliottWave3
CChartObjectElliottWave5
See also
Object types, Graphic objects
2326
Standard Library
CChartObjectElliottWave3
Class CChartObjectElliottWave3 is a class for simplified access to "Correcting Wave" graphic object
properties.
Description
Class CChartObjectElliottWave3 provides access to "Correcting Wave" object properties.
Declaration
class CChartObjectElliottWave3 : public CChartObject
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create
Create
Properties
Degree
Lines
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectElliottWave5
See also
Object types, Graphic objects
2327
Standard Library
Create
Creates graphic object "Correcting Wave".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error.
2328
Standard Library
Return Value
Value of "Degree" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
// property value
Parameters
degree
[in] New value for "Degree" property.
Return Value
true if successful, false if property hasn't changed.
2329
Standard Library
Return Value
Value of "Lines" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// flag value
Parameters
lines
[in] New value for "Lines" property.
Return Value
true if successful, false if flag hasn't changed.
2330
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2331
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened using by function FileOpen(...).
Return Value
true if successful, false if error.
2332
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_ELLIOTWAVE3 for CChartObjectElliottWave3).
2333
Standard Library
CChartObjectElliottWave5
Class CChartObjectElliottWave5 is a class for simplified access to "Impulse Wave" graphic object
properties.
Description
Class CChartObjectElliottWave5 provides access to "Impulse Wave" object properties.
Declaration
class CChartObjectElliottWave5 : public CChartObjectElliottWave3
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2334
Standard Library
Create
Creates graphic object "Impulse Wave".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3,
datetime time4,
double
price4,
datetime time5
double
price5,
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).
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.
2335
Standard Library
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.
Return Value
true if successful, false if error.
2336
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_ELLIOTWAVE5 for CChartObjectElliottWave5).
2337
Standard Library
Shape Objects
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 .
Class name
Object
CChartObjectRectangle
CChartObjectTriangle
CChartObjectEllipse
See also
Object types, Graphic objects
2338
Standard Library
CChartObjectRectangle
Class CChartObjectRectangle is a class for simplified access to "Rectangle" graphic object properties.
Description
Class CChartObjectRectangle provides access to "Rectangle" object properties.
Declaration
class CChartObjectRectangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2339
Standard Library
Create
Creates graphic object "Rectangle".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
long
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2
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).
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.
Return Value
true if successful, false if error
2340
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_RECTANGLE for CChartObjectRectangle).
2341
Standard Library
CChartObjectTriangle
Class CChartObjectTriangle is a class for simplified access to "Triangle" graphic object properties.
Description
Class CChartObjectTriangle provides access to "Triangle" object properties.
Declaration
class CChartObjectTriangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2342
Standard Library
Create
Creates graphic object "Triangle".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
long
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error
2343
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_TRIANGLE for CChartObjectTriangle).
2344
Standard Library
CChartObjectEllipse
Class CChartObjectEllipse is a class for simplified access to "Ellipse" graphic object properties.
Description
Class CChartObjectEllipse provides access to "Ellipse" object properties.
Declaration
class CChartObjectEllipse : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create
Create
Input/output
virtual Type
See also
Object types, Graphic objects
2345
Standard Library
Create
Creates graphic object "Ellipse".
bool Create(
long
chart_id,
// Chart identifier
string
name,
// Object name
int
window,
// Chart window
datetime time1,
double
price1,
datetime time2,
double
price2,
datetime time3,
double
price3
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).
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.
Return Value
true if successful, false if error
2346
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
Return Value
Object type identifier (OBJ_ELLIPSE for CChartObjectEllipse).
2347
Standard Library
Arrow Objects
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 is a certain icon which is associated with a specific 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
CChartObjectArrowUp
Arrow Down
CChartObjectArrowStop
Stop Sign
CChartObjectArrowThumbDown
Thumbs Up
CChartObjectArrowThumbUp
Thumbs Down
CChartObjectArrowLeftPrice
CChartObjectArrowRightPrice
See also
Object types, Methods of Object Binding, Graphic objects
2348
Standard Library
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\ChartObjectsArrows.mqh>
Class Methods
Create
Create
Properties
ArrowCode
Anchor
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Methods of objects binding, Graphic objects
2349
Standard Library
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).
Return Value
true if successful, otherwise false.
Example:
//--- example for CChartObjectArrow::Create
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
CChartObjectArrow arrow;
//--- set object parameters
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181))
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//---
2350
Standard Library
return;
}
//--- use arrow
//--- . . .
}
2351
Standard Library
Return Value
Symbol code of "Arrow" object assigned to the class instance. If there is no object assigned, it
returns 0.
// Code value
Parameters
code
[in] new value for "arrow" code (Wingdings).
Return Value
true if successful, false if code hasn't changed.
Example:
//--- example for CChartObjectArrow::ArrowCode
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
CChartObjectArrow arrow;
char
code=181;
2352
Standard Library
arrow.ArrowCode(code);
}
//--- use arrow
//--- . . .
}
2353
Standard Library
Return Value
Anchor type of "Arrow" object, assigned to the class instance. If there is no object assigned, it
returns WRONG_VALUE.
Parameters
anchor
[in] New anchor type
Return Value
true if successful, false if anchor type hasn't changed.
Example:
//--- example for CChartObject::Anchor
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
CChartObjectArrow arrow;
ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM;
//--- set object parameters
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181))
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//--return;
}
//--- get anchor of arrow
if(arrow.Anchor()!=anchor)
{
//--- set anchor of arrow
arrow.Anchor(anchor);
}
2354
Standard Library
//--- use arrow
//--- . . .
}
2355
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// file handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, otherwise false.
Example:
//--- example for CChartObjectArrow::Save
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
int
file_handle;
CChartObjectArrow arrow;
//--- set object parameters
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181))
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//--return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!arrow.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
FileClose(file_handle);
//--return;
}
FileClose(file_handle);
}
}
2356
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// file handle
Parameters
file_handle
[in] handle of file opened previously using the FileOpen(...) function.
Return Value
true if successful, otherwise false.
Example:
//--- example for CChartObjectArrow::Load
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
int
file_handle;
CChartObjectArrow arrow;
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!arrow.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
FileClose(file_handle);
//--return;
}
FileClose(file_handle);
}
//--- use arrow
//--- . . .
}
2357
Standard Library
Type
Returns graphic object type identifier
virtual int Type() const
Return Value
Object type identifier (for example, OBJ_ARROW for CChartObjectArrow)
Example:
//--- example for CChartObjectArrow::Type
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
CChartObjectArrow arrow;
//--- get arrow type
int type=arrow.Type();
}
2358
Standard Library
CChartObjectArrowCheck
"Arrow Check"
CChartObjectArrowDown
"Arrow Down"
CChartObjectArrowUp
"Arrow Up"
CChartObjectArrowStop
"Arrow Stop"
CChartObjectArrowThumbDown
CChartObjectArrowThumbUp
CChartObjectArrowLeftPrice
CChartObjectArrowRightPrice
Description
Classes "Arrows with fixed code" provide 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;
Title
<ChartObjects\ChartObjectsArrows.mqh>
Class Methods
Create
Create
Properties
ArrowCode
Input/output
virtual Type
2359
Standard Library
See also
Object types, Methods of object binding, Graphic objects
2360
Standard Library
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.
Return Value
true if successful, false if error.
Example:
//--- example for CChartObjectArrowCheck::Create
//--- example for CChartObjectArrowDown::Create
//--- example for CChartObjectArrowUp::Create
//--- example for CChartObjectArrowStop::Create
//--- example for CChartObjectArrowThumbDown::Create
//--- example for CChartObjectArrowThumbUp::Create
//--- example for CChartObjectArrowLeftPrice::Create
//--- example for CChartObjectArrowRightPrice::Create
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
//--- for example, take CChartObjectArrowCheck
CChartObjectArrowCheck arrow;
//--- set object parameters
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(!arrow.Create(0,"ArrowCheck",0,TimeCurrent(),price))
2361
Standard Library
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//--return;
}
//--- use arrow
//--- . . .
}
2362
Standard Library
ArrowCode
Prohibits code changes for "Arrow".
bool ArrowCode(
char code
// code value
Parameters
code
[in] any value
Return Value
Always false.
Example:
//--- example for CChartObjectArrowCheck::ArrowCode
//--- example for CChartObjectArrowDown::ArrowCode
//--- example for CChartObjectArrowUp::ArrowCode
//--- example for CChartObjectArrowStop::ArrowCode
//--- example for CChartObjectArrowThumbDown::ArrowCode
//--- example for CChartObjectArrowThumbUp::ArrowCode
//--- example for CChartObjectArrowLeftPrice::ArrowCode
//--- example for CChartObjectArrowRightPrice::ArrowCode
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
//--- for example, take CChartObjectArrowCheck
CChartObjectArrowCheck arrow;
//--- set object parameters
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(!arrow.Create(0,"ArrowCheck",0,TimeCurrent(),price))
{
//--- arrow create error
printf("Arrow create: Error %d!",GetLastError());
//--return;
}
//--- set code of arrow
if(!arrow.ArrowCode(181))
{
//--- it is not error
printf("Arrow code can not be changed");
}
//--- use arrow
//--- . . .
}
2363
Standard Library
Type
Returns graphic object type identifier
virtual int Type() const
Return Value
Object type identifier (OBJ_ARROW_CHECK for CChartObjectArrowCheck, OBJ_ARROW_DOWN for
CChartObjectArrowDown, OBJ_ARROW_UP for CChartObjectArrowUp, OBJ_ARROW_STOP for
CChartObjectArrowStop,
OBJ_ARROW_THUMB_DOWN
for
CChartObjectArrowThumbDown,
OBJ_ARROW_THUMB_UP
for
CChartObjectArrowThumbUp,
OBJ_ARROW_LEFT_PRICE
for
CChartObjectArrowLeftPrice, OBJ_ARROW_RIGHT_PRICE for CChartObjectArrowRightPrice).
Example:
//--- example for CChartObjectArrowCheck::Type
//--- example for CChartObjectArrowDown::Type
//--- example for CChartObjectArrowUp::Type
//--- example for CChartObjectArrowStop::Type
//--- example for CChartObjectArrowThumbDown::Type
//--- example for CChartObjectArrowThumbUp::Type
//--- example for CChartObjectArrowLeftPrice::Type
//--- example for CChartObjectArrowRightPrice::Type
#include <ChartObjects\ChartObjectsArrows.mqh>
//--void OnStart()
{
//--- for example, take CChartObjectArrowCheck
CChartObjectArrowCheck arrow;
//--- get arrow type
int type=arrow.Type();
}
2364
Standard Library
Control Objects
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 .
Class name
Object
CChartObjectText
CChartObjectLabel
CChartObjectEdit
CChartObjectButton
CChartObjectSubChart
CChartObjectBitmap
CChartObjectBmpLabel
CChartObjectRectLabel
See also
Object types, Graphic objects
2365
Standard Library
CChartObjectText
Class CChartObjectText is a class for simplified access to "Text" graphic object properties.
Description
Class CChartObjectText provides access to "Text" object properties.
Declaration
class CChartObjectText : public CChartObject
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Create
Properties
Angle
Font
FontSize
Anchor
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectLabel
See also
Object types, Object properties, Methods of object binding, Graphic objects
2366
Standard Library
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 coordinate
price
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).
time
[in] Time coordinate of the anchor point.
price
[in] Price coordinate of the anchor point.
Return Value
true if successful, false if error.
2367
Standard Library
Return Value
Value of "Angle" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
// new angle
Parameters
angle
[in] New value for "Angle" property.
Return Value
true if successful, false if property hasn't changed.
2368
Standard Library
Return Value
Value of "Font" property of the object, assigned to the class instance. If there is no object assigned,
it returns "".
// new font
Parameters
font
[in] New value for "Font" property.
Return Value
true if successful, false if property hasn't changed.
2369
Standard Library
Return Value
Value of "FontSize" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
Parameters
size
[in] New value for "Font size" property.
Return Value
true if successful, false if property hasn't changed.
2370
Standard Library
Return Value
Value of "Anchor" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
// new value
Parameters
anchor
[in] New value for "Anchor" property.
Return Value
true if successful, false if property hasn't changed.
2371
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2372
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2373
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_TEXT for CChartObjectText).
2374
Standard Library
CChartObjectLabel
Class CChartObjectLabel is a class for simplified access to "Label" graphic object properties.
Description
Class CChartObjectLabel provides access to "Label" object properties.
Declaration
class CChartObjectLabel : public CChartObjectText
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Create
Properties
X_Distance
Y_Distance
X_Size
Y_Size
Corner
Time
Price
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectEdit
See also
Object types, Object properties, Chart angle, Methods of Object Binding, Graphic objects
2375
Standard Library
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 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.
Return Value
true if successful, false if error.
2376
Standard Library
Return Value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2377
Standard Library
Return Value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2378
Standard Library
X_Size
Gets the value of "X_Size" property.
int X_Size() const
Return Value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
2379
Standard Library
Y_Size
Gets the value of "Y_Size" property.
int Y_Size() const
Return Value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
2380
Standard Library
Return Value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
// new value
Parameters
corner
[in] New value for "Corner" property.
Return Value
true if successful, false if property hasn't changed.
2381
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time
// any value
Parameters
time
[in] Any value of datetime type.
Return Value
always false.
2382
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price(
double price
// any value
Parameters
price
[in] Any value of double type.
Return Value
always false.
2383
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2384
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2385
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_LABEL for CChartObjectLabel).
2386
Standard Library
CChartObjectEdit
Class CChartObjectEdit is a class for simplified access to "Edit" graphic object properties.
Description
Class CChartObjectEdit provides access to "Edit" object properties.
Declaration
class CChartObjectEdit : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Create
Properties
TextAlign
X_Size
Y_Size
BackColor
BorderColor
ReadOnly
Angle
Input/output
virtual Save
virtual Load
virtual Type
Derived classes:
CChartObjectButton
See also
Object types, Object properties, Chart angle, Methods of Object Binding, Graphic objects
2387
Standard Library
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] 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] X size.
sizeY
[in] Y size.
Return Value
true if successful, false if error.
2388
Standard Library
Return Value
Value of "TextAlign" property of the object, assigned to the class instance.
// new value
Parameters
align
[in] New value of "TextAlign" property.
Return Value
true if successful, false if property hasn't changed.
2389
Standard Library
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.
Return Value
true if successful, false if property hasn't changed.
2390
Standard Library
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.
Return Value
true if successful, false if property hasn't changed.
2391
Standard Library
Return Value
Value of "BackColor" property of the object, assigned to the class instance. If there is no object
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New value for "BackColor" property.
Return Value
true if successful, false if property hasn't changed.
2392
Standard Library
Return Value
Value of "Border Color" property of the object, assigned to the class instance. If there is no object
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New value for "Border Color" property.
Return Value
true if successful, false if property hasn't changed.
2393
Standard Library
Return Value
Value of "Read Only" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
bool flag
// new value
Parameters
flag
[in] New value for "Read Only" property.
Return Value
true if successful, false if property hasn't changed.
2394
Standard Library
Angle
Prohibits changes of the "Angle" property.
bool Angle(
double angle
// any value
Parameters
angle
[in] Any value of double type.
Return Value
always false.
2395
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2396
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2397
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_EDIT for CChartObjectEdit).
2398
Standard Library
CChartObjectButton
Class CChartObjectButton is a class for simplified access to "Button" graphic object properties.
Description
Class CChartObjectButton provides access to "Button" object properties.
Declaration
class CChartObjectButton : public CChartObjectEdit
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Create
Properties
State
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Object properties, Chart angle, Methods of object binding, Graphic objects
2399
Standard Library
Return Value
Value of "State" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
X
[in] New value for "State" property.
Return Value
true if successful, false if property hasn't changed.
2400
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2401
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2402
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_BUTTON for CChartObjectButton).
2403
Standard Library
CChartObjectSubChart
Class CChartObjectSubChart is a class for simplified access to "Chart" graphic object properties.
Description
Class CChartObjectSubChart provides access to "Chart" object properties.
Declaration
class CChartObjectSubChart : public CChartObject
Title
#include <ChartObjects\ChartObjectSubChart.mqh>
Class Methods
Create
Create
Properties
X_Distance
Y_Distance
Corner
X_Size
Y_Size
Symbol
Period
Scale
DateScale
PriceScale
Time
Price
Input/output
virtual Save
virtual Load
virtual Type
See also
2404
Standard Library
Object types, Object properties, Chart angle, Graphic objects
2405
Standard Library
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] 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] X size.
sizeY
[in] Y size.
Return Value
true if successful, false if error.
2406
Standard Library
Return Value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2407
Standard Library
Return Value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2408
Standard Library
Return Value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
// new value
Parameters
corner
[in] New value for "Corner" property.
Return Value
true if successful, false if property hasn't changed.
2409
Standard Library
Return Value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Size" property.
Return Value
true if successful, false if property hasn't changed.
2410
Standard Library
Return Value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Size" property.
Return Value
true if successful, false if property hasn't changed.
2411
Standard Library
Return Value
Value of "Symbol" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
// new symbol
Parameters
symbol
[in] New value for "Symbol" property.
Return Value
true if successful, false if property hasn't changed.
2412
Standard Library
Return Value
Value of "Period" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new period
Parameters
period
[in] New value for "Period" property.
Return Value
true if successful, false if property hasn't changed.
2413
Standard Library
Return Value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
// new scale
Parameters
scale
[in] New value for "Scale" property.
Return Value
true if successful, false if property hasn't changed.
2414
Standard Library
Return Value
Value of "DateScale" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// new value
Parameters
scale
[in] New value for "DateScale" property.
Return Value
true if successful, false if property hasn't changed.
2415
Standard Library
Return Value
Value of "PriceScale" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// new value
Parameters
scale
[in] New value for "PriceScale" property.
Return Value
true if successful, false if property hasn't changed.
2416
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time
// any value
Parameters
time
[in] Any value of datetime type.
Return Value
always false.
2417
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price(
double price
// any value
Parameters
price
[in] Any value of double type.
Return Value
always false.
2418
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2419
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2420
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_CHART for CChartObjectSubChart).
2421
Standard Library
CChartObjectBitmap
Class CChartObjectBitmap is a class for simplified access to "Bitmap" graphic object properties.
Description
Class CChartObjectBitmap provides access to "Bitmap" object properties.
Declaration
class CChartObjectBitmap : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create
Create
Properties
BmpFile
X_Offset
Y_Offset
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Object properties, Graphic objects
2422
Standard Library
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 coordinate
price
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).
time
[in] Time coordinate of the anchor point.
price
[in] Price coordinate of the anchor point.
Return Value
true if successful, false if error.
2423
Standard Library
Return Value
Value of "BmpFile" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
name
[in] New value for "BmpFile" property.
Return Value
true if successful, false if property hasn't changed.
2424
Standard Library
Return Value
Value of "X_Offset" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Offset" property.
Return Value
true if successful, false if property hasn't changed.
2425
Standard Library
Return Value
Value of "Y_Offset" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Offset" property.
Return Value
true if successful, false if property hasn't changed.
2426
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2427
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2428
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_BITMAP for CChartObjectBitmap).
2429
Standard Library
CChartObjectBmpLabel
Class CChartObjectBmpLabel is a class for simplified access to "Bitmap Label" graphic object
properties.
Description
Class CChartObjectBmpLabel provides access to "Bitmap Label" object properties.
Declaration
class CChartObjectBmpLabel : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create
Create
Properties
X_Distance
Y_Distance
X_Offset
Y_Offset
Corner
X_Size
Y_Size
BmpFileOn
BmpFileOff
State
Time
Price
Input/output
virtual Save
virtual Load
2430
Standard Library
virtual Type
See also
Object types, Object properties, Chart angle, Graphic objects
2431
Standard Library
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 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.
Return Value
true if successful, false if error.
2432
Standard Library
Return Value
Value of "X_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2433
Standard Library
Return Value
Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Distance" property.
Return Value
true if successful, false if property hasn't changed.
2434
Standard Library
Return Value
Value of "X_Offset" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
X
[in] New value for "X_Offset" property.
Return Value
true if successful, false if property hasn't changed.
2435
Standard Library
Return Value
Value of "Y_Offset" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
Y
[in] New value for "Y_Offset" property.
Return Value
true if successful, false if property hasn't changed.
2436
Standard Library
Return Value
Value of "Corner" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
// new value
Parameters
corner
[in] New value for "Corner" property.
Return Value
true if successful, false if property hasn't changed.
2437
Standard Library
X_Size
Gets the value of "X_Size" property.
int X_Size() const
Return Value
Value of "X_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
2438
Standard Library
Y_Size
Gets the value of "Y_Size" property.
int Y_Size() const
Return Value
Value of "Y_Size" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
2439
Standard Library
Return Value
Value of "BmpFileOn" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
// file name
Parameters
name
[in] New value for "BmpFileOn" property.
Return Value
true if successful, false if property hasn't changed.
2440
Standard Library
Return Value
Value of "BmpFileOff" property of the object, assigned to the class instance. If there is no object
assigned, it returns "".
// file name
Parameters
name
[in] New value for "BmpFileOff" property.
Return Value
true if successful, false if property hasn't changed.
2441
Standard Library
Return Value
Value of "State" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
state
[in] New value for "State" property.
Return Value
true if successful, false if property hasn't changed.
2442
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time(
datetime time
// any value
Parameters
time
[in] Any value of datetime type.
Return Value
always false.
2443
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price(
double price
// any value
Parameters
price
[in] Any value of double type.
Return Value
always false.
2444
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2445
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2446
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_BITMAP_LABEL for CChartObjectBmpLabel).
2447
Standard Library
CChartObjectRectLabel
Class CChartObjectRectLabel is a class for simplified access to "Rectangle Label" graphic object
properties.
Description
Class CChartObjectRectLabel provides access to "Rectangle Label" object properties.
Declaration
class CChartObjectRectLabel : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create
Create
Properties
X_Size
Y_Size
BackColor
Angle
A stub method
BorderType
Input/output
virtual Save
virtual Load
virtual Type
See also
Object types, Object properties, Graphic objects
2448
Standard Library
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.
Return Value
true if successful, false if error.
2449
Standard Library
X_Size
Sets the value of "X_Size" property.
bool X_Size(
int size
// Horizontal size
Parameters
size
[in] New horizontal size.
Return Value
true if successful, false if the property hasn't been changed.
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.
2450
Standard Library
Y_Size
Sets the value of "Y_Size" property.
bool Y_Size(
int size
// Vertical size
Parameters
size
[in] New vertical size.
Return Value
true if successful, false if the property hasn't been changed.
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.
2451
Standard Library
BackColor
Gets the background color.
color BackColor() const
Return 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.
Return Value
true if successful, false if property hasn't been changed.
2452
Standard Library
Angle
A stub method.
bool Angle(
double angle
// any value
Parameters
angle
[in] Any value of double type.
Return Value
Always false.
2453
Standard Library
BorderType
Gets border type.
int BorderType() const
Return 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.
Return Value
true if successful, false if property hasn't been changed.
2454
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2455
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen function.
Return Value
true if successful, false if error.
2456
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (OBJ_RECTANGLE_LABEL for CChartObjectRectangleLabel).
2457
Standard Library
CCanvas
CCanvas is a class for simplified creation of custom images.
Description
CCanvas provides creation of a graphical resource (with or without binding to a chart object) and
drawing graphic primitives.
Declaration
class CCanvas
Title
#include <Canvas\Canvas.mqh>
CreateBitmap
CreateBitmapLabel
Destroy
Properties
ChartObjectName
ResourceName
Width
Height
LineStyleSet
Resize
Data access
PixelGet
2458
Standard Library
PixelSet
Drawing primitives
LineVertical
LineHorizontal
Line
Polyline
Draws a polyline
Polygon
Draws a polygon
Rectangle
Draws a rectangle
Circle
Draws a circle
Triangle
Draws a triangle
FillCircle
FillTriangle
Fill
Fills an area
Draws a pixel
LineAA
Draws a line
PolylineAA
Draws a polyline
PolygonAA
Draws a polygon
TriangleAA
Draws a triangle
CircleAA
Draws a circle
Text
FontSet
FontNameSet
FontSizeSet
FontFlagsSet
FontAngleSet
FontGet
FontNameGet
FontSizeGet
FontFlagsGet
2459
Standard Library
FontAngleGet
TextOut
Displays text
TextWidth
TextHeight
TextSize
Transparency
TransparentLevelSet
Input/output
LoadFromFile
2460
Standard Library
ChartObjectName
Receives the name of a bound chart object.
string ChartObjectName();
Return Value
the name of a bound chart object
2461
Standard Library
Circle
Draws a circle
void Circle(
int
x,
// X coordinate
int
y,
// Y coordinate
int
r,
// radius
// color
);
Parameters
x
[in] X coordinate of the center of the circle.
y
[in] Y coordinate of the center of the circle.
r
[in] Circle radius.
clr
[in] Color in ARGB format.
2462
Standard Library
CircleAA
Draws a circle using antialiasing algorithm
void CircleAA(
const int
x,
// X coordinate
const int
y,
// Y coordinate
const double r,
// radius
const uint
// color
clr
);
Parameters
x
[in] X coordinate of the center of the circle.
y
[in] Y coordinate of the center of the circle.
r
[in] Circle radius.
clr
[in] Color in ARGB format.
2463
Standard Library
Create
Creates a graphical resource without binding to a chart object.
virtual bool Create(
const string
name,
// name
const int
width,
// width
const int
height,
// height
ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA
// format
);
Parameters
name
[in] Basis for a graphical resource name. A resource name is generated during the creation by
adding a pseudorandom string.
width
[in] Width (size along X axis) in pixels.
height
[in] Height (size along Y axis) in pixels.
clrfmt=COLOR_FORMAT_XRGB_NOALPHA
[in] Color processing method. See ResourceCreate() function description to learn more about color
processing methods.
Return Value
true - if successful, otherwise - false
2464
Standard Library
CreateBitmap
Creates a graphical resource bound to a chart object.
1. Creates a graphical resource in the main window of the current chart.
bool CreateBitmap(
const string
name,
// name
const datetime
time,
// time
const double
price,
// price
const int
width,
// width
const int
height,
// height
ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA
// format
);
chart_id,
// chart ID
const int
subwin,
// subwindow number
const string
name,
// name
const datetime
time,
// time
const double
price,
// price
const int
width,
// width
const int
height,
// height
ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA
);
Parameters
chart_id
[in] Chart ID for creating an object.
subwin
[in] Chart subwindow number for creating an object.
name
[in] Chart object name and a basis for a graphical resource name.
time
[in] Chart object anchor point time coordinate.
price
[in] Chart object anchor point price coordinate.
width
[in] Graphical resource width (size along X axis) in pixels.
height
[in] Graphical resource height (size along Y axis) in pixels.
clrfmt=COLOR_FORMAT_XRGB_NOALPHA
// format
2465
Standard Library
[in] Color processing method. See ResourceCreate() function description to learn more about color
processing methods.
Return Value
true - if successful, otherwise - false
Note
If the first function version is used, the object is created in the main window of the current chart.
Object size coincides with the size of a graphical resource.
2466
Standard Library
CreateBitmapLabel
Creates a graphical resource bound to a chart object.
1. Creates a graphical resource in the main window of the current chart.
bool CreateBitmapLabel(
const string
name,
// name
const int
x,
// X coordinate
const int
y,
// Y coordinate
const int
width,
// width
const int
height,
// height
ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA
// format
);
chart_id,
// chart ID
const int
subwin,
// subwindow number
const string
name,
// name
const int
x,
// X coordinate
const int
y,
// Y coordinate
const int
width,
// width
const int
height,
// height
ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA
);
Parameters
chart_id
[in] Chart ID for creating an object.
subwin
[in] Chart subwindow number for creating an object.
name
[in] Chart object name and a basis for a graphical resource name.
x
[in] Chart object anchor point X coordinate.
y
[in] Chart object anchor point Y coordinate.
width
[in] Graphical resource width (size along X axis) in pixels.
height
[in] Graphical resource height (size along Y axis) in pixels.
clrfmt=COLOR_FORMAT_XRGB_NOALPHA
// format
2467
Standard Library
[in] Color processing method. See ResourceCreate() function description to learn more about color
processing methods.
Return Value
true - if successful, otherwise - false
Note
If the first function version is used, the object is created in the main window of the current chart.
Object size coincides with the size of a graphical resource.
2468
Standard Library
Destroy
Destroys a graphical resource.
void Destroy();
Note
If a graphical resource has been bound to a chart object, the latter is deleted.
2469
Standard Library
Erase
Erases or fills with the specified color.
void Erase(
const uint clr=0
// color
);
Parameters
clr=0
[in] Color in ARGB format.
2470
Standard Library
Fill
Fills an area.
void Fill(
int
x,
// X coordinate
int
y,
// Y coordinate
// color
);
Parameters
x
[in] X coordinate of filling starting point.
y
[in] Y coordinate of filling starting point.
clr
[in] Color in ARGB format.
2471
Standard Library
FillCircle
Draws a filled circle.
void FillCircle(
int
x,
// X coordinate
int
y,
// Y coordinate
int
r,
// radius
// color
);
Parameters
x
[in] X coordinate of a filled circle center.
y
[in] Y coordinate of a filled circle center.
r
[in] Filled circle radius.
clr
[in] Color in ARGB format.
2472
Standard Library
FillRectangle
Draws a filled rectangle.
void FillRectangle(
int
x1,
// X coordinate
int
y1,
// Y coordinate
int
x2,
// X coordinate
int
y2,
// Y coordinate
// color
);
Parameters
x1
[in] X coordinate of the first point forming a rectangle.
y1
[in] Y coordinate of the first point forming a rectangle.
x2
[in] X coordinate of the second point forming a rectangle.
y2
[in] Y coordinate of the second point forming a rectangle.
clr
[in] Color in ARGB format.
2473
Standard Library
FillTriangle
Draws a filled triangle.
void FillTriangle(
int
x1,
// X coordinate
int
y1,
// Y coordinate
int
x2,
// X coordinate
int
y2,
// Y coordinate
int
x3,
// X coordinate
int
y3,
// Y coordinate
// color
);
Parameters
x1
[in] X coordinate of the triangle's first corner.
y1
[in] Y coordinate of the triangle's first corner.
x2
[in] X coordinate of the triangle's second corner.
y2
[in] Y coordinate of the triangle's second corner.
x3
[in] X coordinate of the triangle's third corner.
y3
[in] Y coordinate of the triangle's third corner.
clr
[in] Color in ARGB format.
2474
Standard Library
FontAngleGet
Receives font slope angle.
uint FontAngleGet();
Return Value
font slope angle
2475
Standard Library
FontAngleSet
Sets font slope angle.
bool FontAngleSet(
uint angle
// angle
);
Parameters
angle
[in] Font slope angle in tenths of a degree.
Return Value
true - if successful, otherwise - false
2476
Standard Library
FontFlagsGet
Receives font flags.
uint FontFlagsGet();
Return Value
font flags
2477
Standard Library
FontFlagsSet
Sets font flags.
bool FontFlagsSet(
uint flags
// flags
);
Parameters
flags
[in] Font creation flags. See TextSetFont() function description to learn more about the flags.
Return Value
true - if successful, otherwise - false
2478
Standard Library
FontGet
Receives the current font parameters.
void FontGet(
string& name,
// name
int&
size,
// size
uint&
flags,
// flags
uint&
angle
// slope angle
);
Parameters
name
[out] Reference to the variable for returning a font name.
size
[out] Reference to the variable for returning a font size.
flags
[out] Reference to the variable for returning font flags.
angle
[out] Reference to the variable for returning a font slope angle.
2479
Standard Library
FontNameGet
Receives font name.
string FontNameGet();
Return Value
font name
2480
Standard Library
FontNameSet
Sets font name.
bool FontNameSet(
string name
// name
);
Parameters
name
[in] Font name. For example, "Arial".
Return Value
true - if successful, otherwise - false
2481
Standard Library
FontSet
Sets the current font.
bool FontSet(
const string name,
// name
const int
size,
// size
const uint
flags=0,
// flags
const uint
angle=0
// angle
);
Parameters
name
[in] Font name. For example, "Arial".
size
[in] Font size. See TextSetFont() function description to learn more about setting a size.
flags=0
[in] Font creation flags. See TextSetFont() function description to learn more about the flags.
angle=0
[in] Font slope angle in tenths of a degree.
Return Value
true - if successful, otherwise - false
2482
Standard Library
FontSizeGet
Receives font size.
int FontSizeGet();
Return Value
font size
2483
Standard Library
FontSizeSet
Sets font size.
bool FontSizeSet(
int size
// size
);
Parameters
size
[in] Font size. See TextSetFont() function description to learn more about setting a size.
Return Value
true - if successful, otherwise - false
2484
Standard Library
Height
Receives the height of a graphical resource.
int Height();
Return Value
height of a graphical resource
2485
Standard Library
Line
Draws a segment of a freehand line.
void Line(
int
x1,
// X coordinate
int
y1,
// Y coordinate
int
x2,
// X coordinate
int
y2,
// Y coordinate
// color
);
Parameters
x1
[in] X coordinate of the segment's first point.
y1
[in] Y coordinate of the segment's first point.
x2
[in] X coordinate of the segment's second point.
y2
[in] Y coordinate of the segment's second point.
clr
[in] Color in ARGB format.
2486
Standard Library
LineAA
Draws a segment of a freehand line using antialiasing algorithm.
void LineAA(
const int
x1,
// X coordinate
const int
y1,
// Y coordinate
const int
x2,
// X coordinate
const int
y2,
// Y coordinate
// color
// line style
);
Parameters
x1
[in] X coordinate of the segment's first point.
y1
[in] Y coordinate of the segment's first point.
x2
[in] X coordinate of the segment's second point.
y2
[in] Y coordinate of the segment's second point.
clr
[in] Color in ARGB format.
style=UINT_MAX
[in] Line style is one of ENUM_LINE_STYLE enumeration's values or a custom value.
2487
Standard Library
LineHorizontal
Draws a segment of a horizontal line.
void LineHorizontal(
int
x1,
// X coordinate
int
x2,
// X coordinate
int
y,
// Y coordinate
// color
);
Parameters
x1
[in] Segment's X coordinate.
x2
[in] X coordinate of the segment's first point.
y
[in] Y coordinate of the segment's second point.
clr
[in] Color in ARGB format.
2488
Standard Library
LineStyleSet
Sets the line style.
void LineStyleSet(
const uint style
// style
);
Parameters
style
[in] Line style.
Note
The input parameter can have any of ENUM_LINE_STYLE enumeration values. Besides, it is possible
to create a custom line drawing style.
2489
Standard Library
LineVertical
Draws a segment of a vertical line.
void LineVertical(
int
x,
// X coordinate
int
y1,
// Y coordinate
int
y2,
// Y coordinate
// color
);
Parameters
x
[in] Segment's X coordinate.
y1
[in] Y coordinate of the segment's first point.
y2
[in] Y coordinate of the segment's second point.
clr
[in] Color in ARGB format.
2490
Standard Library
LoadFromFile
Reads an image from a BMP file.
bool LoadFromFile(
const string filename
// file name
);
Parameters
filename
[in] File name (including "BMP" extension).
Return Value
true - if successful, otherwise - false
2491
Standard Library
PixelGet
Receives color of the point with the specified coordinates.
uint PixelGet(
const int x,
// X coordinate
const int y
// Y coordinate
);
Parameters
x
[in] Point's X coordinate.
y
[in] Point's Y coordinate.
Return Value
Point color in ARGB format.
2492
Standard Library
PixelSet
Sets color of the point with the specified coordinates.
void PixelSet(
const int
x,
// X coordinate
const int
y,
// Y coordinate
// color
);
Parameters
x
[in] Point's X coordinate.
y
[in] Point's Y coordinate.
clr
[in] Color in ARGB format.
2493
Standard Library
PixelSetAA
Draws a point using antialiasing algorithm.
void PixelSetAA(
const double x,
// X coordinate
const double y,
// Y coordinate
const uint
// color
clr
);
Parameters
x
[in] Point's X coordinate.
y
[in] Point's Y coordinate.
clr
[in] Color in ARGB format.
2494
Standard Library
Polygon
Draws a polygon.
void Polygon(
int&
x[],
// array of X coordinates
int&
y[],
// array of Y coordinates
// color
);
Parameters
x[]
[in] Array of X coordinates of a polygon points.
y[]
[in] Array of Y coordinates of a polygon points.
clr
[in] Color in ARGB format.
2495
Standard Library
PolygonAA
Draws a polygon using antialiasing algorithm.
void PolygonAA(
int&
x[],
// array of X coordinates
int&
y[],
// array of Y coordinates
// color
// line style
);
Parameters
x[]
[in] Array of X coordinates of a polygon points.
y[]
[in] Array of Y coordinates of a polygon points.
clr
[in] Color in ARGB format.
style=UINT_MAX
[in] Line style is one of ENUM_LINE_STYLE enumeration's values or a custom value.
2496
Standard Library
Polyline
Draws a polyline.
void Polyline(
int&
x[],
// array of X coordinates
int&
y[],
// array of Y coordinates
// color
);
Parameters
x[]
[in] Array of X coordinates of a polyline.
y[]
[in] Array of Y coordinates of a polyline.
clr
[in] Color in ARGB format.
2497
Standard Library
PolylineAA
Draws a polyline using antialiasing algorithm.
void PolylineAA(
int&
x[],
// array of X coordinates
int&
y[],
// array of Y coordinates
// color
// line style
);
Parameters
x[]
[in] Array of X coordinates of a polyline.
y[]
[in] Array of Y coordinates of a polyline.
clr
[in] Color in ARGB format.
style=UINT_MAX
[in] Line style is one of ENUM_LINE_STYLE enumeration's values or a custom value.
2498
Standard Library
Rectangle
Draws a rectangle using two points.
void Rectangle(
int
x1,
// X coordinate
int
y1,
// Y coordinate
int
x2,
// X coordinate
int
y2,
// Y coordinate
// color
);
Parameters
x1
[in] X coordinate of the first point forming a rectangle.
y1
[in] Y coordinate of the first point forming a rectangle.
x2
[in] X coordinate of the second point forming a rectangle.
y2
[in] Y coordinate of the second point forming a rectangle.
clr
[in] Color in ARGB format.
2499
Standard Library
Resize
Resizes a graphical resource.
bool Resize(
const int width,
// width
// height
);
Parameters
width
[in] New width of a graphical resource.
height
[in] New height of a graphical resource.
Return Value
true - if successful, otherwise - false
Note
When resizing, the previous image is not saved.
2500
Standard Library
ResourceName
Receives the name of a graphical resource.
string ResourceName();
Return Value
name of a graphical resource
2501
Standard Library
TextHeight
Receives the text height.
int TextHeight(
const string text
// text
);
Parameters
text
[in] Text for measuring.
Return Value
text height in pixels
Note
The current font is used for measuring the text.
2502
Standard Library
TextOut
Displays text.
void TextOut(
int
x,
// X coordinate
int
y,
// Y coordinate
string
text,
// text
// color
uint
// alignment
alignment=0
);
Parameters
x
[in] Text anchor's X coordinate.
y
[in] Text anchor's Y coordinate.
text
[in] Text to be displayed.
clr
[in] Color in ARGB format.
alignment=0
[in] Text anchoring method. See TextOut() function description to learn more about anchoring
methods.
Note
The current font is used to display the text.
2503
Standard Library
TextSize
Receives the text size.
void TextSize(
const string text,
// text
int&
width,
// width
int&
height
// height
);
Parameters
text
[in] Text for measuring.
width
[out] Reference to the variable for returning a text width.
height
[out] Reference to the variable for returning a text height.
Note
The current font is used to measure the text.
2504
Standard Library
TextWidth
Receives the text width.
int TextWidth(
const string text
// text
);
Parameters
text
[in] Text for measuring.
Return Value
text height in pixels
Note
The current font is used to measure the text.
2505
Standard Library
TransparentLevelSet
Sets transparency level.
void TransparentLevelSet(
const uchar value
// value
);
Parameters
value
[in] New value of the transparency level.
Note
0 stands for full transparency, while 255 - for full opacity.
Setting of a transparency level affects all that was previously drawn. The specified transparency
level does not affect further constructions.
2506
Standard Library
Triangle
Draws a triangle.
void Triangle(
int
x1,
// X coordinate
int
y1,
// Y coordinate
int
x2,
// X coordinate
int
y2,
// Y coordinate
int
x3,
// X coordinate
int
y3,
// Y coordinate
// color
);
Parameters
x1
[in] X coordinate of the triangle's first corner.
y1
[in] Y coordinate of the triangle's first corner.
x2
[in] X coordinate of the triangle's second corner.
y2
[in] Y coordinate of the triangle's second corner.
x3
[in] X coordinate of the triangle's third corner.
y3
[in] Y coordinate of the triangle's third corner.
clr
[in] Color in ARGB format.
2507
Standard Library
TriangleAA
Draws a triangle using antialiasing algorithm.
void TriangleAA(
const int
x1,
// X coordinate
const int
y1,
// Y coordinate
const int
x2,
// X coordinate
const int
y2,
// Y coordinate
const int
x3,
// X coordinate
const int
y3,
// Y coordinate
// color
// line style
);
Parameters
x1
[in] X coordinate of the triangle's first corner.
y1
[in] Y coordinate of the triangle's first corner.
x2
[in] X coordinate of the triangle's second corner.
y2
[in] Y coordinate of the triangle's second corner.
x3
[in] X coordinate of the triangle's third corner.
y3
[in] Y coordinate of the triangle's third corner.
clr
[in] Color in ARGB format.
style=UINT_MAX
[in] Line style is one of ENUM_LINE_STYLE enumeration's values or a custom value.
2508
Standard Library
Update
Displays changes on the screen.
void Update(
const bool redraw=true
// flag
);
Parameters
redraw=true
Flag of a chart redrawing necessity.
2509
Standard Library
Width
Receives the width of a graphical resource.
int Width();
Return Value
graphical resource width
2510
Standard Library
CChart
Class CChart is a class for simplified access to "Chart" graphic object properties.
Description
Class CChart provides access to "Chart" object properties.
Declaration
class CChart : public CObject
Title
#include <Charts\Chart.mqh>
Class Methods
Access to protected data
ChartID
General properties
Mode
Foreground
Shift
ShiftSize
AutoScroll
Scale
ScaleFix
ScaleFix_11
FixedMax
FixedMin
ScalePPB
PointsPerBar
Show properties
2511
Standard Library
ShowOHLC
ShowLineBid
ShowLineAsk
ShowLastLine
ShowPeriodSep
ShowGrid
ShowVolumes
ShowObjectDescr
ShowDateScale
ShowPriceScale
Color properties
ColorBackground
ColorForeground
ColorGrid
ColorBarUp
ColorBarDown
ColorCandleBull
ColorCandleBear
ColorChartLine
ColorVolumes
2512
Standard Library
ColorLineBid
ColorLineAsk
ColorLineLast
ColorStopLevels
WindowsTotal
WindowIsVisible
WindowHandle
FirstVisibleBar
WidthInBars
WidthInPixels
HeightInPixels
PriceMin
PriceMax
Properties
Attach
FirstChart
NextChart
Open
Detach
Close
BringToTop
EventObjectCreate
EventObjectDelete
2513
Standard Library
Indicators
IndicatorAdd
IndicatorDelete
IndicatorsTotal
IndicatorName
Navigation
Navigate
Period
Redraw
GetInteger
SetInteger
GetDouble
SetDouble
GetString
SetString
SetSymbolPeriod
ApplyTemplate
ScreenShot
WindowOnDropped
PriceOnDropped
TimeOnDropped
value
value
value
of
of
of
the
the
the
2514
Standard Library
XOnDropped
YOnDropped
Input/Output
virtual Save
virtual Load
virtual Type
2515
Standard Library
ChartID
Returns identifier of the chart.
long ChartID() const
Return Value
Chart identifier, assigned to the class instance. If there is no object assigned, it returns -1.
2516
Standard Library
Return Value
Value of "Mode" property of the object, assigned to the class instance. If there is no object
assigned, it returns WRONG_VALUE.
Parameters
mode
[in] Chart mode (candle, bar or line) of ENUM_CHART_MODE enumeration.
Return Value
true if successful, false if mode hasn't changed.
2517
Standard Library
Return Value
Value of "Foreground" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
foreground
[in] New value for "Foreground" property.
Return Value
true if successful, false if property hasn't changed.
2518
Standard Library
Return Value
Value of "Shift" property of the object, assigned to the class instance. If there is no object assigned,
it returns false.
Parameters
shift
[in] New value for "Shift" property.
Return Value
true if successful, false if property hasn't changed.
2519
Standard Library
Return Value
Value of "ShiftSize" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
Parameters
shift_size
[in] New value for "ShiftSize" property (in percents).
Return Value
true if successful, false if property hasn't changed.
2520
Standard Library
Return Value
Value of "AutoScroll" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
autoscroll
[in] New value for "Autoscroll" property.
Return Value
true if successful, false if property hasn't changed.
2521
Standard Library
Return Value
Value of "Scale" property of the object, assigned to the class instance. If there is no object
assigned, it returns 0.
// new value
Parameters
scale
[in] New value for "Scale" property.
Return Value
true if successful, false if property hasn't changed.
2522
Standard Library
Return Value
Value of "ScaleFix" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// new value
Parameters
scale_fix
[in] New value for "ScaleFix" property.
Return Value
true if successful, false if property hasn't changed.
2523
Standard Library
Return Value
Value of "ScaleFix_11" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// new value
Parameters
scale_11
[in] New value for "ScaleFix_11" property.
Return Value
true if successful, false if property hasn't changed.
2524
Standard Library
Return Value
Value of "FixedMax" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
Parameters
max
[in] New value for "FixedMax" property.
Return Value
true if successful, false if property hasn't changed.
2525
Standard Library
Return Value
Value of "FixedMin" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
Parameters
max
[in] New value for "FixedMin" property.
Return Value
true if successful, false if property hasn't changed.
2526
Standard Library
Return Value
Value of "PointsPerBar" property of the object, assigned to the class instance. If there is no object
assigned, it returns EMPTY_VALUE.
Parameters
ppb
[in] New value for scale (in points per bar).
Return Value
true if successful, false if scale hasn't changed.
2527
Standard Library
Return Value
Value of "ScalePPB" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
Parameters
scale_ppb
[in] New value for "ScalePPB" property.
Return Value
true if successful, false if property hasn't changed.
2528
Standard Library
Return Value
Value of "ShowOHLC" property of the object, assigned to the class instance. If there is no object
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowOHLC" property.
Return Value
true if successful, false if property hasn't changed.
2529
Standard Library
Return Value
Value of "ShowLineBid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowLineBid" property.
Return Value
true if successful, false if property hasn't changed.
2530
Standard Library
Return Value
Value of "ShowLineAsk" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowLineAsk" property.
Return Value
true if successful, false if property hasn't changed.
2531
Standard Library
Return Value
Value of "ShowLastLine" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
Parameters
show
[in] New value for "ShowLastLine" property.
Return Value
true if successful, false if property hasn't changed.
2532
Standard Library
Return Value
Value of "ShowPeriodSep" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowPeriodSep" property.
Return Value
true if successful, false if property hasn't changed.
2533
Standard Library
Return Value
Value of "ShowGrid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowGrid" property.
Return Value
true if successful, false if property hasn't changed.
2534
Standard Library
Return Value
Value of "ShowVolumes" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// new value
Parameters
show
[in] New value for "ShowVolumes" property.
Return Value
true if successful, false if property hasn't changed.
2535
Standard Library
Return Value
Value of "ShowObjectDescr" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns false.
// New value
Parameters
show
[in] New value for "ShowObjectDescr" property.
Return Value
true if successful, false if property hasn't changed.
2536
Standard Library
ShowDateScale
Sets new value for "ShowDateScale" property.
bool ShowDateScale(
bool show
// New value
Parameters
show
[in] New value for "ShowDateScale" property.
Return Value
true if successful, false if property hasn't changed.
2537
Standard Library
ShowPriceScale
Sets new value for "ShowPriceScale" property.
bool ShowPriceScale(
bool show
// New value
Parameters
show
[in] New value for "ShowPriceScale" property.
Return Value
true if successful, false if property hasn't changed.
2538
Standard Library
Return Value
Value of "ColorBackground" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New background color.
Return Value
true if successful, false if color hasn't changed.
2539
Standard Library
Return Value
Value of "ColorForeground" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
// New color
Parameters
new_color
[in] New color for axes, scale and OHLC string.
Return Value
true if successful, false if color hasn't changed.
2540
Standard Library
Return Value
Value of "ColorGrid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New grid color.
Return Value
true if successful, false if color hasn't changed.
2541
Standard Library
Return Value
Value of "ColorBarUp" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color for bull bars.
Return Value
true if successful, false if color hasn't changed.
2542
Standard Library
Return Value
Value of "ColorBarDown" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color for bear bars.
Return Value
true if successful, false if color hasn't changed.
2543
Standard Library
Return Value
Value of "ColorCandleBull" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the bull candle body.
Return Value
true if successful, false if color hasn't changed.
2544
Standard Library
Return Value
Value of "ColorCandleBear" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the bear candle body.
Return Value
true if successful, false if color hasn't changed.
2545
Standard Library
Return Value
Value of "ColorChartLine" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the chart lines (Doji candles).
Return Value
true if successful, false if color hasn't changed.
2546
Standard Library
Return Value
Value of "ColorVolumes" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the volumes (open position levels).
Return Value
true if successful, false if color hasn't changed.
2547
Standard Library
Return Value
Value of "ColorLineBid" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color for Bid line.
Return Value
true if successful, false if color hasn't changed.
2548
Standard Library
Return Value
Value of "ColorLineAsk" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color for Ask line.
Return Value
true if successful, false if color hasn't changed.
2549
Standard Library
Return Value
Value of "ColorLineLast" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the last deal price line.
Return Value
true if successful, false if color hasn't changed.
2550
Standard Library
Return Value
Value of "ColorStopLevels" property of the chart, assigned to the class instance. If there is no chart
assigned, it returns CLR_NONE.
Parameters
new_color
[in] New color of the Stop Loss and Take Profit price levels.
Return Value
true if successful, false if color hasn't changed.
2551
Standard Library
VisibleBars
Gets total number of visible chart bars.
int VisibleBars() const
Return Value
Gets total number of visible bars of the chart, assigned to the class instance. If there is no chart
assigned, it returns 0.
2552
Standard Library
WindowsTotal
Gets total number of chart windows, including the chart indicator subwindows.
int WindowsTotal() const
Return Value
Total number of windows, including the chart indicator subwindows, assigned to the class instance.
If there is no chart assigned, it returns 0.
2553
Standard Library
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).
Return Value
Returns visibility flag of the specified chart subwindow, assigned to the chart instance. If there is
no chart assigned, it returns false.
2554
Standard Library
WindowHandle
Gets window handle of the chart (HWND).
int WindowHandle() const
Return Value
Window handle of the chart, assigned to the chart instance. If there is no chart assigned, it returns
INVALID_HANDLE.
2555
Standard Library
FirstVisibleBar
Gets the number of the first visible bar of the chart.
int FirstVisibleBar() const
Return Value
Number of the first visible bar of the chart, assigned to the chart instance. If there is no chart
assigned, it returns -1.
2556
Standard Library
WidthInBars
Gets window width in bars.
int WidthInBars() const
Return Value
Window width in chart bars, assigned to the chart instance. If there is no chart assigned, it returns
0.
2557
Standard Library
WidthInPixels
Gets subwindow width in pixels.
int WidthInPixels() const
Return Value
Subwindow width in chart pixels, assigned to the chart instance. If there is no chart assigned, it
returns 0.
2558
Standard Library
HeightInPixels
Gets subwindow height in pixels.
int HeightInPixels(
int num
// subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Return Value
Subwindow height in chart pixels, assigned to the chart instance. If there is no chart assigned, it
returns 0.
2559
Standard Library
PriceMin
Gets minimal price of the specified subwindow.
double PriceMin(
int num
// subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Return Value
Minimal price value of the chart, assigned to the class instance. If there is not chart assigned, it
returns EMPTY_VALUE.
2560
Standard Library
PriceMax
Gets maximal price of the specified subwindow.
double PriceMax(
int num
// subwindow number
) const
Parameters
num
[in] Subwindow number (0 means base window).
Return Value
Maximal price value of the chart, assigned to the class instance. If there is not chart assigned, it
returns EMPTY_VALUE.
2561
Standard Library
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.
2562
Standard Library
FirstChart
Assigns the first chart of the client terminal to the class instance.
void FirstChart()
2563
Standard Library
NextChart
Assigns the next chart of the client terminal to the class instance.
void NextChart()
2564
Standard Library
Open
Opens chart with specified parameters and assign it to the class instance.
long Open(
const string
symbol_name,
ENUM_TIMEFRAMES timeframe
// Symbol name
// 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.
Return Value
Chart identifier.
2565
Standard Library
Detach
Detaches chart from the class instance.
void Detach()
2566
Standard Library
Close
Closes chart, assigned to the class instance.
void Close()
2567
Standard Library
BringToTop
Show chart on top of other charts.
bool BringToTop() const
Return Value
true if successful, false if error.
2568
Standard Library
EventObjectCreate
Sets a flag to send notifications of an event of new object creation to all MQL5-programs on a chart.
bool EventObjectCreate(
bool flag
// flag
Parameters
flag
[in] New flag value.
Return Value
true if successful, false - if flag hasn't been changed.
2569
Standard Library
EventObjectDelete
Sets a flag to send notifications of an event of object deletion to all MQL5-programs on a chart.
bool EventObjectDelete(
bool flag
// flag
Parameters
flag
[in] New flag value.
Return Value
true if successful, false - if flag hasn't been changed.
2570
Standard Library
IndicatorAdd
Adds an indicator with the specified handle into a specified chart window.
bool IndicatorAdd(
int
sub_win
int
handle
);
Parameters
sub_win
[in] The number of the chart sub-window. 0 means the main chart window. if the number of a notexisting window is specified, a new window will be created.
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
IndicatorDelete(), IndicatorsTotal(), IndicatorName().
2571
Standard Library
IndicatorDelete
Removes an indicator with a specified name from the specified chart window.
bool IndicatorDelete(
int
sub_win
const string
name
);
Parameters
sub_win
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
const name
[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 IndicatorName()
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 IndicatorDelete() function is identified by the short
name.
See also
IndicatorAdd(), IndicatorsTotal(), IndicatorName(), iCustom(), IndicatorCreate(),
IndicatorSetString().
2572
Standard Library
IndicatorsTotal
Returns the number of all indicators applied to the specified chart window.
int IndicatorsTotal(
int
sub_win
);
Parameters
sub_win
[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
GetInteger() function.
See also
IndicatorAdd(), IndicatorDelete(), IndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorSetString().
2573
Standard Library
IndicatorName
Returns the short name of the indicator by the index in the indicators list on the specified chart
window.
string IndicatorName(
int
sub_win
int
index
// index of the indicator in the list of indicators added to the chat subwindo
);
Parameters
sub_win
[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 IndicatorsTotal() 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 IndicatorDelete() function is identified by the short
name.
See also
IndicatorAdd(), IndicatorDelete, IndicatorsTotal, iCustom(), IndicatorCreate(), IndicatorSetString().
2574
Standard Library
Navigate
Navigates the chart.
bool Navigate(
ENUM_CHART_POSITION position,
// Position
int
// Shift
shift=0
Parameters
position
[in] Value of ENUM_CHART_POSITION enumeration.
shift=0
[in] Number of bars to shift.
Return Value
true if successful, false if chart hasn't navigated.
2575
Standard Library
Symbol
Gets symbol of the chart.
string Symbol() const
Return Value
Symbol of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
2576
Standard Library
Period
Gets period of the chart.
ENUM_TIMEFRAMES Period() const
Return Value
Period of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
2577
Standard Library
Redraw
Redraws chart, assigned to the class instance.
void Redraw()
2578
Standard Library
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.
1. Immediately returns the property value.
long GetInteger(
ENUM_CHART_PROPERTY_INTEGER prop_id,
// property identifier
int
// subwindow number
sub_window=0
) 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
) 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().
2579
Standard Library
SetInteger
Sets new value for the property of the integer type.
bool SetInteger(
ENUM_CHART_PROPERTY_INTEGER prop_id,
// property identifier
long
// new value
value
Parameters
prop_id
[in] Property identifier (ENUM_CHART_PROPERTY_INTEGER enumeration).
value
[in] New value of the property.
Return Value
true if successful, false if property of the integer type hasn't changed.
2580
Standard Library
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.
1. Immediately returns the property value.
double GetDouble(
ENUM_CHART_PROPERTY_DOUBLE prop_id,
// property identifier
int
// subwindow number
sub_window=0
) 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
) 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().
2581
Standard Library
SetDouble
Sets new value for the property of the double type.
bool SetDouble(
ENUM_CHART_PROPERTY_DOUBLE prop_id,
// property identifier
double
// new value
value
Parameters
prop_id
[in] Property idenitifier (ENUM_CHART_PROPERTY_DOUBLE enumeration).
value
[in] New value for the property.
Return Value
true if successful, false if property of the double type hasn't changed.
2582
Standard Library
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.
1. Immediately returns the property value.
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
) 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().
2583
Standard Library
SetString
Sets new value for the property of the string type.
bool SetString(
ENUM_CHART_PROPERTY_STRING prop_id,
// property identifier
string
value
Parameters
prop_id
[in] Property idenitifier (ENUM_CHART_PROPERTY_STRING enumeration).
value
[in] New value for the property.
Return Value
true if successful, false if property of the string type hasn't changed.
2584
Standard Library
SetSymbolPeriod
Changes symbol and period of the chart, assigned to the class instance.
bool SetSymbolPeriod(
const string
symbol_name,
ENUM_TIMEFRAMES timeframe
// Symbol
// 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.
Return Value
true if successful, false if property hasn't changed.
2585
Standard Library
ApplyTemplate
Applies specified template to the chart.
bool ApplyTemplate(
const string filename
Parameters
filename
[in] File name of the template.
Return Value
true if successful, false if template hasn't been applied.
2586
Standard Library
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.
Return Value
true if successful, false if error.
2587
Standard Library
WindowOnDropped
Gets chart subwindow number corresponding to the object (expert or script) drop point.
int WindowOnDropped() const
Return Value
Chart subwindow number of the object drop point. 0 means main chart window.
2588
Standard Library
PriceOnDropped
Gets price coordinate corresponding to the object (expert or script) drop point.
double PriceOnDropped() const
Return Value
Price coordinate of the object drop point.
2589
Standard Library
TimeOnDropped
Gets time coordinate corresponding to the object (expert or script) drop point.
datetime TimeOnDropped() const
Return Value
Time coordinate of the object drop point.
2590
Standard Library
XOnDropped
Gets X coordinate corresponding to the object (expert or script) drop point.
int XOnDropped() const
Return Value
X coordinate of the object drop point.
2591
Standard Library
YOnDropped
Gets Y coordinate corresponding to the object (expert or script) drop point.
int YOnDropped() const
Return Value
Y coordinate of the object drop point.
2592
Standard Library
Save
Saves object parameters to file.
virtual bool Save(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen(...) function.
Return Value
true if successful, false if error.
2593
Standard Library
Load
Loads object parameters from file.
virtual bool Load(
int file_handle
// File handle
Parameters
file_handle
[in] handle of the binary file already opened by FileOpen(...) function.
Return Value
true if successful, false if error.
2594
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
Return Value
Object type identifier (0x1111 for CChart).
2595
Standard Library
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 (in terms of file operations) is located in the working directory of the
terminal in the Include\Files folder.
Class
Description
CFile
CFileBin
CFileTxt
2596
Standard Library
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
Handle
Filename
Flags
SetUnicode
SetCommon
Opens file
Close
Closes file
Delete
Deletes file
IsExist
Copy
Copies file
Move
Renames/moves file
Size
Tell
Seek
Flush
IsEnding
IsLineEnding
2597
Standard Library
FolderCreate
Creates folder
FolderDelete
Deletes folder
FolderClean
Clears folder
Search methods
FileFindFirst
FileFindNext
FileFindClose
Derived classes:
CFileBin
CFileTxt
2598
Standard Library
Handle
Gets file handle of the opened file.
int Handle()
Return Value
Handle of the opened file, assigned to the class instance. If there is no file assigned, it returns -1.
2599
Standard Library
FileName
Gets file name of the opened file.
string FileName()
Return Value
File name of the opened file, assigned to the class instance. If there is no file assigned, it returns
"".
2600
Standard Library
Flags
Gets flags of the opened file.
int Flags()
Return Value
Flags of the opened file, assigned to the class instance.
2601
Standard Library
SetUnicode
Sets/Clears the FILE_UNICODE flag.
void SetUnicode(
bool unicode
Parameters
unicode
[in] New value for FILE_UNICODE flag.
Note
The result of string operations is dependent on the FILE_UNICODE flag. If it is 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.
2602
Standard Library
SetCommon
Sets/Clears the FILE_COMMON flag.
void SetCommon(
bool common
Parameters
common
[in] New value for FILE_COMMON flag.
Note
The FILE_COMMON flag determines the current work folder. If it is false, the local terminal folder is
used as the current working folder. If it is true, the Common Data Folder is used as the current work
folder. If the file is already opened, the flag cannot be changed.
2603
Standard Library
Open
Opens 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.
Return Value
Handle of the opened file.
Note
The work folder is dependent on the FILE_COMMON flag, defined by SetCommon() method.
2604
Standard Library
Close
Closes file, assigned to the class instance.
void Close()
2605
Standard Library
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
The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
2606
Standard Library
IsExist
Checks file for existence
bool IsExist(
const string file_name
// File name
Parameters
file_name
[in] Name of the file to check.
Return Value
true, if file exists.
2607
Standard Library
Copy
Copies a file.
bool Copy(
const string src_name,
int
// Flag
src_flag,
int
// Flags
dst_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).
Return Value
true if successful, false if it hasn't been copied.
2608
Standard Library
Move
Renames/moves file.
bool Move(
const string src_name,
int
// Flag
src_flag,
int
// Flags
dst_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).
Return Value
true if successful, false if it hasn't been moved.
2609
Standard Library
Size
Gets file size in bytes.
ulong Size()
Return Value
File size in bytes. If there isn't any file assigned, it returns ULONG_MAX.
2610
Standard Library
Tell
Gets the current file position.
ulong Tell()
Return Value
The current file position. If there isn't any file assigned, it returns ULONG_MAX.
2611
Standard Library
Seek
Sets current file position.
void Seek(
long
offset,
ENUM_FILE_POSITION origin
// Offset
// Origin
Parameters
offset
[in] File offset in bytes (can be negative).
origin
[in] Origin of the offset.
Return Value
true if successful, false if file position hasn't been changed.
2612
Standard Library
Flush
Flushes all of the file input/output buffer data on disk.
void Flush()
2613
Standard Library
IsEnding
Checks file for end. It's used during the file read operations.
bool IsEnding()
Return Value
true if end of file has been achieved after read or seek operation.
2614
Standard Library
IsLineEnding
Checks file for end of line. It's used during the file read operations.
bool IsLineEnding()
Return Value
true if end of line has been achieved after the txt or csv file read operation (CR-LF chars).
2615
Standard Library
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.
Return Value
true if successful, and false if the folder hasn't been created.
Note
The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
2616
Standard Library
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.
Return Value
true if successful, and false if the folder hasn't been deleted.
Note
The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
2617
Standard Library
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.
Return Value
true if successful, and false if the folder hasn't been cleaned.
Note
The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
2618
Standard Library
FileFindFirst
Begins file search using the specified filter.
int FileFindFirst(
const string filter,
// Search Filter
string&
// Reference to string
file_name
Parameters
filter
[in] Search filter.
file_name
[out] The reference to string for the first file found.
Return Value
If successful, it returns the handle that can be used for further file search using FileFindNext, or it
returns INVALID_HANDLE if there isn't any file corresponding to the filter specified.
Note
The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
2619
Standard Library
FileFindNext
Continues file search started by the FileFindFirst() method.
bool FileFindNext(
int
search_handle,
string& file_name
// Search handle
// 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.
Return Value
true if successful, false if there isn't any file, corresponding to the filter specified.
2620
Standard Library
FileFindClose
Closes search handle.
void FileFindClose(
int search_handle
// Search handle
Parameters
search_handle
[in] Search handle, returned by FileFindFirst() method.
2621
Standard Library
CFileBin
CFileBin is a class for simplified access to binary files.
Description
Class CFileBin provides an access to binary files.
Declaration
class CFileBin: public CFile
Title
#include <Files\FileBin.mqh>
Class Methods
Open methods
Open
Write methods
WriteChar
WriteShort
WriteInteger
WriteLong
WriteFloat
WriteDouble
WriteString
WriteCharArray
WriteShortArray
WriteIntegerArray
WriteLongArray
WriteFloatArray
WriteDoubleArray
WriteObject
Read methods
ReadChar
ReadShort
2622
Standard Library
ReadInteger
ReadLong
ReadFloat
ReadDouble
ReadString
ReadCharArray
ReadShortArray
ReadIntegerArray
ReadLongArray
ReadFloatArray
ReadDoubleArray
ReadObject
2623
Standard Library
Open
Opens 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 (the FILE_BIN flag is set forcibly).
Return Value
Handle of the opened file.
2624
Standard Library
WriteChar
Writes char or uchar type variable to file.
uint WriteChar(
char value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2625
Standard Library
WriteShort
Writes short or ushort type variable to file.
uint WriteShort(
short value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2626
Standard Library
WriteInteger
Writes int or uint type variable to file.
uint WriteInteger(
int value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2627
Standard Library
WriteLong
Writes long or ulong type variable to file.
uint WriteLong(
long value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2628
Standard Library
WriteFloat
Writes float type variable to file.
uint WriteFloat(
float value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2629
Standard Library
WriteDouble
Writes double type variable to file.
uint WriteDouble(
double value
// Value
Parameters
value
[in] Variable to write.
Return Value
Number of bytes written.
2630
Standard Library
WriteString
Writes string type variable to file.
uint WriteString(
const string value
// Value
Parameters
value
[in] String to write.
Return Value
Number of bytes written.
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.
Return Value
Number of bytes written.
2631
Standard Library
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).
Return Value
Number of bytes written.
2632
Standard Library
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
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).
Return Value
Number of bytes written.
2633
Standard Library
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
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).
Return Value
Number of bytes written.
2634
Standard Library
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
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).
Return Value
Number of bytes written.
2635
Standard Library
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
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).
Return Value
Number of bytes written.
2636
Standard Library
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
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).
Return Value
Number of bytes written.
2637
Standard Library
WriteObject
Writes data of the CObject class inheritor instance to file.
bool WriteObject(
CObject* object
Parameters
object
[in] Reference to the CObject class inheritor instance to write.
Return Value
true if successful, false if data hasn't been written.
2638
Standard Library
ReadChar
Reads char or uchar type variable from file.
bool ReadChar(
char& value
// Target variable
Parameters
value
[in] Target variable of type char.
Return Value
true if successful, false if data hasn't been read.
2639
Standard Library
ReadShort
Reads short or ushort type variable from file.
bool ReadShort(
short& value
)
Parameters
value
[in] Target variable of type short or ushort.
Return Value
true if successful, false if data hasn't been read.
2640
Standard Library
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.
Return Value
true if successful, false if data hasn't been read.
2641
Standard Library
ReadLong
Reads long or ulong type variable from file.
bool ReadLong(
long& value
)
Parameters
value
[in] Target variable of type long or ulong.
Return Value
true if successful, false if data hasn't been read.
2642
Standard Library
ReadFloat
Reads float type variable from file.
bool ReadFloat(
float& value
// Target variable
Parameters
value
[in] Target variable of type float.
Return Value
true if successful, false if data hasn't been read.
2643
Standard Library
ReadDouble
Reads double type variable from file.
bool ReadDouble(
double& value
)
Parameters
value
[in] Target variable of type double.
Return Value
true if successful, false if data hasn't been read.
2644
Standard Library
ReadString
Reads string type variable from file.
bool ReadString(
string& value
// Target string
Parameters
value
[in] Target variable of type string.
Return Value
true if successful, false if data hasn't been read.
ReadString
Reads string type variable from file.
bool ReadString(
string& value
)
Parameters
value
[in] Target variable of type string.
Return Value
true if successful, false if data hasn't been read.
2645
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2646
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2647
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2648
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2649
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2650
Standard Library
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
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).
Return Value
true if successful, false if data hasn't been read.
2651
Standard Library
ReadObject
Reads data of the CObject class inheritor instance from file.
bool ReadObject(
CObject* object
Parameters
object
[in] Pointer to the CObject class inheritor instance to read.
Return Value
true if successful, false if data hasn't been read.
2652
Standard Library
CFileTxt
CFileTxt is a class for simplified access to text files.
Description
Class CFileTxt provides an access to text files.
Declaration
class CFileTxt: public CFile
Title
#include <Files\FileTxt.mqh>
Class Methods
Open methods
Open
Write methods
WriteString
Read methods
ReadString
2653
Standard Library
Open
Opens 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).
Return Value
Opened file handle.
2654
Standard Library
WriteString
Writes string type variable to file.
uint WriteString(
const string value
// String to write
Parameters
value
[in] String to write.
Return Value
Number of bytes written.
2655
Standard Library
ReadString
Reads string type variable from file.
string ReadString()
Return Value
String which has been read.
2656
Standard Library
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 (in terms of string operations) is located in the working directory of the
terminal in the Include\Strings folder.
Class
Description
CString
2657
Standard Library
CString
CString is a class for simplified access to the variables of string type.
Description
Class CString 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
Data access methods
Str
Gets a string
Len
Copy
Copies a string
Fill methods
Fill
Assign
Assigns a string
Append
Appends a string
Insert
Inserts a string
Compare methods
Compare
Compares a string
CompareNoCase
Substring methods
Left
Right
Mid
Trim/delete methods
Trim
2658
Standard Library
TrimLeft
TrimRight
Clear
Clears a string
Convert methods
ToUpper
ToLower
Reverse
Reverses a string
Search methods
Find
FindRev
Remove
Replace
Replaces a substring
2659
Standard Library
Str
Gets a string.
string Str() const;
Return Value
Copy of a string.
2660
Standard Library
Len
Gets length of a string.
uint Len() const;
Return Value
Length of a string.
2661
Standard Library
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.
2662
Standard Library
Fill
Fills a string with specified char.
bool Fill(
short character
// Character
Parameters
character
[in] Character for filling.
Return Value
true if successful, false if a string hasn't been filled.
2663
Standard Library
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.
2664
Standard Library
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.
2665
Standard Library
Insert
Inserts a string to the specified position.
uint Insert(
uint
pos,
// Position
// String to insert
Parameters
pos
[in] Insert position.
str
[in] String to insert.
Return Value
Resulted string length.
Insert
Inserts a string to the specified position to the CString class instance.
uint Insert(
uint
pos,
CString* str
// Position
// Object descriptor
Parameters
pos
[in] Insert position.
str
[in] CString class object descriptor to insert.
Return Value
Resulted string length.
2666
Standard Library
Compare
Compares a string.
int Compare(
const string str
// String to compare
) const;
Parameters
str
[in] String to compare.
Return Value
It returns 0 if both strings are equal, -1 if the class string is lower than the string to compare, and 1 if the class string is greater than the 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.
Return Value
It returns 0 if both strings are equal, -1 if the class string is lower than the string to compare, and 1 if the class string is greater than the string to compare.
2667
Standard Library
CompareNoCase
Performs a case insensitive string comparison.
int CompareNoCase(
const string str
// String to compare
) const;
Parameters
str
[in] String to compare.
Return 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.
Return 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.
2668
Standard Library
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.
Return Value
Resulted substring.
2669
Standard Library
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.
Return Value
Resulted substring.
2670
Standard Library
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.
Return Value
Resulted substring.
2671
Standard Library
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
Parameters
targets
[in] Set of characters to remove.
Return Value
Number of characters removed.
Example:
//--- example for CString::Trim
#include <Strings\String.mqh>
//--void OnStart()
{
CString str;
//--str.Assign("
\t\tABCD\r\n");
2672
Standard Library
TrimLeft
Removes all leading occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimLeft(
const string targets
Parameters
targets
[in] Set of characters to remove.
Return Value
Number of characters removed.
2673
Standard Library
TrimRight
Removes all trailing occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimRight(
const string targets
Parameters
targets
[in] Set of characters to remove.
Return Value
Number of characters removed.
2674
Standard Library
Clear
Clears a string.
bool Clear()
Return Value
true if successful, false if a string hasn't been cleared.
2675
Standard Library
ToUpper
Converts a string to uppercase.
bool ToUpper()
Return Value
true if successful, false if a string hasn't been converted.
2676
Standard Library
ToLower
Converts a string to lowercase.
bool ToLower()
Return Value
true if successful, false if a string hasn't been converted.
2677
Standard Library
Reverse
Reverses a string.
void Reverse()
2678
Standard Library
Find
Searches for the first match of a substring.
int Find(
uint
start,
// Position
// 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.
Return Value
The index of the first character that matches the requested substring; -1 if the substring is not
found.
2679
Standard Library
FindRev
Searches for the last match of a substring.
int FindRev(
const string substring
// Substring
) const;
Parameters
substring
[in] A substring to search for.
Return Value
The index of the last character that matches the requested substring; -1 if the substring is not
found.
2680
Standard Library
Remove
Deletes a substring from a string.
uint Remove(
const string substring
// Substring to remove
Parameters
substring
[in] A substring to search for.
Return Value
Number of substrings deleted.
2681
Standard Library
Replace
Replaces a substring from a string.
uint Replace(
const string substring,
// Substring to replace
// New substring
Parameters
substring
[in] A substring to search for.
newstring
[in] A substring to replace for.
Return Value
Number of substrings replaced.
2682
Standard Library
Description
Base classes
Timeseries classes
Trend Indicators
Oscillators
Volume Indicators
Custom indicators
2683
Standard Library
Description
CSpreadBuffer
CTimeBuffer
CTickVolumeBuffer
CRealVolumeBuffer
CDoubleBuffer
COpenBuffer
CHighBuffer
CLowBuffer
CCloseBuffer
CIndicatorBuffer
CSeries
CPriceSeries
CIndicator
CIndicators
2684
Standard Library
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
Size
Settings
SetSymbolPeriod
virtual RefreshCurrent
2685
Standard Library
Size
Sets buffer size.
void Size(
const int size
// new size
Parameters
size
[in] New buffer size.
2686
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
const string
symbol,
// symbol
// period
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
2687
Standard Library
At
Gets the buffer element by index.
int At(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2688
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2689
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2690
Standard Library
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
Size
Settings
SetSymbolPeriod
virtual RefreshCurrent
2691
Standard Library
Size
Sets buffer size.
void Size(
const int size
// new size
Parameters
size
[in] New buffer size.
2692
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
const string
symbol,
// symbol
// period
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
2693
Standard Library
At
Gets the buffer element by index.
long At(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2694
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2695
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2696
Standard Library
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
Size
Settings
SetSymbolPeriod
virtual RefreshCurrent
2697
Standard Library
Size
Sets buffer size.
void Size(
const int size
// new size
Parameters
size
[in] New buffer size.
2698
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
const string
symbol,
// symbol
// period
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
2699
Standard Library
At
Gets the buffer element by index.
long At(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2700
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2701
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2702
Standard Library
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
Size
Settings
SetSymbolPeriod
virtual RefreshCurrent
2703
Standard Library
Size
Sets buffer size.
void Size(
const int size
// new size
Parameters
size
[in] New buffer size.
2704
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
const string
symbol,
// symbol
// period
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
2705
Standard Library
At
Gets the buffer element by index.
long At(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2706
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2707
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2708
Standard Library
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
Size
Settings
SetSymbolPeriod
virtual RefreshCurrent
2709
Standard Library
Size
Sets buffer size.
void Size(
const int size
// new size
Parameters
size
[in] New buffer size.
2710
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod(
const string
symbol,
// symbol
// period
Parameters
symbol
[in] New symbol.
period
[in] New period (ENUM_TIMEFRAMES enumeration).
2711
Standard Library
At
Gets the buffer element by index.
double At(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2712
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2713
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2714
Standard Library
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
Data Update Methods
virtual Refresh
virtual RefreshCurrent
2715
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2716
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2717
Standard Library
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
Data Update Methods
virtual Refresh
virtual RefreshCurrent
2718
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2719
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2720
Standard Library
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
Data Update Methods
virtual Refresh
virtual RefreshCurrent
2721
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2722
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2723
Standard Library
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
Data Update Methods
virtual Refresh
virtual RefreshCurrent
2724
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Return Value
true if successful, false if the buffer hasn't been updated.
2725
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Return Value
true if successful, false if the buffer hasn't been updated.
2726
Standard Library
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
Name
RefreshCurrent
2727
Standard Library
Offset
Gets offset of the buffer.
int Offset() const
Return Value
Buffer offset.
Offset
Sets offset of the buffer.
void Offset(
const int offset
// offset
Parameters
offset
[in] New buffer offset.
2728
Standard Library
Name
Gets the name of the buffer.
string Name() const
Return Value
Name of the buffer.
Name
Sets the name of the buffer.
void Name(
const string name
// name
Parameters
name
[in] New name of the buffer.
2729
Standard Library
At
Gets buffer element by index.
double At(
int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
Buffer element with the specified index.
2730
Standard Library
Refresh
Updates the whole buffer.
bool Refresh(
const int handle,
// handle
// buffer number
Parameters
handle
[in] Handle of the indicator.
num
[in] Buffer index of the indicator.
Return Value
true if successful, false if the buffer hasn't been updated.
2731
Standard Library
RefreshCurrent
Updates the current (zeroth) buffer element.
bool RefreshCurrent(
const int handle,
// buffer number
Parameters
handle
[in] Handle of the indicator.
num
[in] Buffer number.
Return Value
true if successful, false if the buffer hasn't been updated.
2732
Standard Library
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
BuffersTotal
Timeframe
Symbol
Period
RefreshCurrent
2733
Standard Library
Name
Gets the name of timeseries or indicator
string Name() const
Return Value
The name of timeseries or indicator.
2734
Standard Library
BuffersTotal
Gets the number of buffers of timeseries or indicator.
int BuffersTotal() const
Return Value
The number of buffers of timeseries or indicator.
Note
The timeseries has an only one buffer.
2735
Standard Library
Timeframe
Gets the timeframe flag of timeseries or indicator.
int Timeframe() const
Return Value
The timeframe flag of timeseries or indicator.
Note
It's the visibility flag of some timeframes.
2736
Standard Library
Symbol
Gets the symbol of timeseries or indicator.
string Symbol() const
Return Value
The symbol of timeseries or indicator.
2737
Standard Library
Period
Gets the period of timeseries or indicator.
ENUM_TIMEFRAMES Period() const
Return Value
The period (value of ENUM_TIMEFRAMES enumeration) of timeseries or indicator.
2738
Standard Library
RefreshCurrent
Sets a flag to update the current values of timeseries or indicator.
string RefreshCurrent(
const bool flag
// new flag
Parameters
flag
[in] New flag.
Return Value
None.
2739
Standard Library
BufferSize
Returns the amount of data available in timeseries buffer or indicator buffer.
int BufferSize() const
Return Value
Amount of data available in timeseries buffer or indicator buffer.
2740
Standard Library
BufferResize
Sets buffer size of timeseries or indicator.
virtual bool BufferResize(
const int size
// new size
Parameters
size
[in] New size of the buffers.
Return Value
true if successful, false otherwise.
Note
All the timeseries or indicator buffers have the same size.
2741
Standard Library
Refresh
Updates the data of timeseries or indicator.
virtual void Refresh(
const int flags
// flags
Parameters
flags
[in] Timeframes to update (flag).
2742
Standard Library
PeriodDescription
Gets the string representation of the specified ENUM_TIMEFRAMES enumeration.
string PeriodDescription(
const int val=0
// value
Parameters
val=0
[in] Value to convert.
Return Value
The string representation of the specified ENUM_TIMEFRAMES enumeration.
Note
If the value isn't specified or equal to zero, it returns the timeframe of timeseries or indicator.
2743
Standard Library
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
virtual BufferResize
virtual MinValue
virtual MaxIndex
virtual MaxValue
2744
Standard Library
BufferResize
Sets new size of the buffer.
virtual void BufferResize(
const int size
// new size
Parameters
size
[in] New buffer size.
2745
Standard Library
GetData
Gets the specified buffer element by index.
double GetData(
const int index
// index
) const
Parameters
index
[in] Index of buffer element.
Return Value
The buffer element with the specified index or EMPTY_VALUE.
2746
Standard Library
Refresh
Updates the timeseries data
virtual void Refresh(
const int flags=OBJ_ALL_PERIODS
// timeframe flags
Parameters
flags=OBJ_ALL_PERIODS
[in] Timeframes to update (flag).
2747
Standard Library
MinIndex
Gets the index of minimal element in the specified range.
virtual int MinIndex(
const int start,
// starting index
) const
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
Return Value
The index of minimal element in the specified range, or -1 in the case of error.
2748
Standard Library
MinValue
Gets the value and index of minimal element in the specified range.
virtual double MinValue(
const int
start,
// starting index
const int
count,
int&
index
) const
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of integer type.
Return Value
The value of minimal element of the buffer in the specified range, or EMPTY_VALUE if error.
Note
The index of minimal element is stored in the variable index.
2749
Standard Library
MaxIndex
Gets the index of maximal element in the specified range.
virtual int MaxIndex(
const int start,
// starting index
) const
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
Return Value
The index of the maximal element in the specified range, or -1 in the case of error.
2750
Standard Library
MaxValue
Gets the value and index of maximal element in the specified range.
virtual double MaxValue(
const int
start,
// starting index
const int
count,
int&
index
) const
Parameters
start
[in] Starting index.
count
[in] Number of elements to proceed.
index
[out] Reference to the variable of integer type.
Return Value
The value of maximal element of the buffer in the specified range, or EMPTY_VALUE if error.
Note
The index of maximal element is stored in the variable index.
2751
Standard Library
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
Handle
Status
FullRelease
Creation
Create
BufferResize
MinValue
Maximum
MaxValue
Conversion of Enumerations
2752
Standard Library
MethodDescription
ENUM_MA_METHOD
PriceDescription
VolumeDescription
ENUM_APPLIED_PRICE
DeleteFromChart
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
2753
Standard Library
CiOsMA
CiRSI
CiRVI
CiSAR
CiStdDev
CiStochastic
CiTEMA
CiTriX
CiVIDyA
CiVolumes
CiWPR
2754
Standard Library
Handle
Gets the indicator's handle.
int Handle() const
Return Value
Handle of the indicator.
2755
Standard Library
Status
Gets the status of the indicator.
string Status() const
Return Value
The status of indicator creation.
2756
Standard Library
FullRelease
Sets a flag to release the handle of the indicator.
void FullRelease(
const bool flag=true
// flag
Parameters
flag
[in] New value of the handle release flag.
2757
Standard Library
Create
Creates the indicator with specified parameters.
bool Create(
const string
symbol,
// symbol
// period
const ENUM_INDICATOR
type,
// type
const int
num_params,
// number of parameters
const MqlParam&
params[]
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.
Return Value
true if successful, false if indicator hasn't been created.
2758
Standard Library
BufferResize
Sets the size of the indicator's buffer.
virtual bool BufferResize(
const int size
// size
Parameters
size
[in] New buffer size.
Return Value
true if successful, false otherwise.
Note
All the indicator's buffers have the same size.
2759
Standard Library
BarsCalculated
Returns the number of calculated data for the indicator.
int BarsCalculated() const;
Return Value
Returns the amount of calculated data in the indicator buffer or -1 in the case of error (data not
calculated yet).
2760
Standard Library
GetData
Gets the specified element from the specified buffer of the indicator. Refresh() should be called for
working with recent data before using the method.
double GetData(
const int buffer_num,
// buffer number
// element index
) const
Parameters
buffer_num
[in] Buffer number.
index
[in] Element index.
Return Value
If successful, it returns the numerical value of element, or EMPTY_VALUE in the case of error.
GetData
Gets the data from the indicator's buffer by starting position and number of necessary data.
int GetData(
const int
start_pos,
// position
const int
count,
const int
buffer_num,
// buffer number
double&
buffer[]
) 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] Reference to the target array for the data.
Return Value
If successful, it returns the number of elements, received
from the specified indicator buffer,
otherwise -1.
GetData
2000-2016, MetaQuotes Software Corp.
2761
Standard Library
Gets the data from the indicator's buffer by start time and number of necessary data.
int GetData(
const datetime start_time,
// starting time
const int
count,
const int
buffer_num,
// buffer number
double&
buffer[]
) 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.
Return Value
If successful, it returns the number of elements, received
from the specified indicator buffer,
otherwise -1.
GetData
Gets the data from the indicator's buffer by start and stop time and number of necessary data.
int GetData(
const datetime start_time,
// start time
// stop time
const int
buffer_num,
// number of buffer
double&
buffer[]
) 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.
2762
Standard Library
Return Value
If successful, it returns the number of elements, received
from the specified indicator buffer,
otherwise -1.
2763
Standard Library
Refresh
Updates the indicator's data. It is recommended calling the method before using GetData().
virtual void Refresh(
int flags=OBJ_ALL_PERIODS
// flags
Parameters
flags=OBJ_ALL_PERIODS
[in] Timeframe update flags.
2764
Standard Library
Minimum
Returns the index of minimal element of the specified buffer in a specified range.
int Minimum(
const int buffer_num,
// buffer number
// starting index
) 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.
Return Value
Index of the minimal element of the specified buffer in a specified range.
2765
Standard Library
MinValue
Returns the value and index of minimal element of the specified buffer in a specified range.
double MinValue(
const int
buffer_num,
// buffer number
const int
start,
// starting index
const int
count,
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.
Return 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.
2766
Standard Library
Maximum
Returns the index of maximal element of the specified buffer in a specified range.
int Maximum(
const int buffer_num,
// buffer number
// starting index
) 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.
Return Value
Index of the maximal element of the specified buffer in a specified range.
2767
Standard Library
MaxValue
Returns the value and index of maximal element of the specified buffer in a specified range.
double MaxValue(
const int
buffer_num,
// buffer number
const int
start,
// starting index
const int
count,
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.
Return 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.
2768
Standard Library
MethodDescription
The function returns the value of ENUM_MA_METHOD enumeration as a string.
string MethodDescription(
const int val
// value
) const
Parameters
val
[in] Value of ENUM_MA_METHOD enumeration.
Return Value
The value of ENUM_MA_METHOD enumeration as a string.
2769
Standard Library
PriceDescription
The method returns the value of ENUM_APPLIED_PRICE enumeration as a string.
string PriceDescription(
const int val
// value
) const
Parameters
val
[in] Value of ENUM_APPLIED_PRICE enumeration.
Return Value
The value of ENUM_APPLIED_PRICE enumeration as a string.
2770
Standard Library
VolumeDescription
The method returns the value of ENUM_APPLIED_VOLUME enumeration as a string.
string VolumeDescription(
const int val
// value
) const
Parameters
val
[in] Value of ENUM_APPLIED_VOLUME enumeration.
Return Value
The value of ENUM_APPLIED_VOLUME enumeration as a string.
2771
Standard Library
AddToChart
Adds the indicator to the chart.
bool AddToChart(
const long chart,
// chart ID
// chart subwindow
Parameters
chart
[in] Chart ID.
subwin
[in] Chart subwindow.
Return Value
true if successful, false if error.
2772
Standard Library
DeleteFromChart
Deletes the indicator from the chart.
bool DeleteFromChart(
const long chart,
// chart ID
// chart subwindow
Parameters
chart
[in] Chart ID.
subwin
[in] Chart subwindow.
Return Value
true if successful, false if error.
2773
Standard Library
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
2774
Standard Library
Create
It creates the indicator with the specified parameters.
CIndicator* Create(
const string
symbol,
// Symbol name
// Period
const ENUM_INDICATOR
type,
// Indicator's type
const int
count,
// Number of parameters
const MqlParam&
params
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.
Return Value
If successful, it returns the reference to the created indicator, and NULL if the indicator hasn't been
created.
2775
Standard Library
Refresh
Updates data for all technical indicators in the collection.
int Refresh()
Return Value
It returns the updated timeframe flags (formed as an object visibility flags).
2776
Standard Library
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
CiTime
CiTickVolume
CiRealVolume
CiOpen
CiHigh
CiLow
CiClose
2777
Standard Library
CiSpread
CiSpread is a class designed for access to spreads of the bars in the history.
Description
The CiSpread class provides an access to spread historical data.
Declaration
class CiSpread: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries
BufferResize
2778
Standard Library
Create
Creates a timeseries with the specified parameters for access to the spreads history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2779
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize(
int size
// new size
Parameters
size
[in] New buffer size.
2780
Standard Library
GetData
Gets the element of timeseries by index.
int GetData(
int index
// index
) const
Parameters
index
[in] Index of the element needed.
Return Value
The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
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
2000-2016, MetaQuotes Software Corp.
2781
Standard Library
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
int&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2782
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh(
int flags
// flags
Parameters
flags
[in] Timeframe flags.
2783
Standard Library
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
BufferResize
2784
Standard Library
Create
Creates a timeseries with the specified parameters for access to the opening times of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2785
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize(
int size
// new size
Parameters
size
[in] New buffer size.
2786
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData(
int index
// index
) const
Parameters
index
[in] Index of the element needed.
Return Value
The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
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
2000-2016, MetaQuotes Software Corp.
2787
Standard Library
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
long&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2788
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh(
int flags
// flags
Parameters
flags
[in] Timeframe flags.
2789
Standard Library
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
BufferResize
2790
Standard Library
Create
Creates a timeseries with the specified parameters for access to the tick volumes of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2791
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize(
int size
// new size
Parameters
size
[in] New buffer size.
2792
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData(
int index
// index
) const
Parameters
index
[in] Index of the element needed.
Return Value
The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
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
2000-2016, MetaQuotes Software Corp.
2793
Standard Library
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
long&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2794
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh(
int flags
// flags
Parameters
flags
[in] Timeframe flags.
2795
Standard Library
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
BufferResize
2796
Standard Library
Create
Creates a timeseries with the specified parameters for access to the real volumes of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2797
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize(
int size
// new size
Parameters
size
[in] New buffer size.
2798
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData(
int index
// index
) const
Parameters
index
[in] Index of the element needed.
Return Value
The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
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
2000-2016, MetaQuotes Software Corp.
2799
Standard Library
[in] Starting time.
count
[in] Number of elements needed.
buffer
[in] Reference to the target array for data.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
long&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2800
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh(
int flags
// flags
Parameters
flags
[in] Timeframe flags.
2801
Standard Library
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 CPriceSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries
2802
Standard Library
Create
Creates a timeseries with the specified parameters for access to the open prices of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2803
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time,
// starting time
int
// number of elements
double&
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
2804
Standard Library
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
double&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2805
Standard Library
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 CPriceSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries
2806
Standard Library
Create
Creates a timeseries with the specified parameters for access to the high prices of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2807
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time,
// starting time
int
// number of elements
double&
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
2808
Standard Library
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
double&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2809
Standard Library
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 CPriceSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries
2810
Standard Library
Create
Creates a timeseries with the specified parameters for access to the low prices of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2811
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time,
// starting time
int
// number of elements
double&
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
2812
Standard Library
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
double&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2813
Standard Library
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 CPriceSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods
Create
Creates a timeseries
2814
Standard Library
Create
Creates a timeseries with the specified parameters for access to the closing prices of the bars in the
history.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// symbol
// period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if timeseries hasn't been created.
2815
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData(
int
start_pos,
// starting position
int
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData(
datetime start_time,
// starting time
int
// number of elements
double&
count,
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.
Return Value
>=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
2816
Standard Library
int GetData(
datetime start_time,
// starting time
datetime stop_time,
// stop time
double&
// target array
buffer
) const
Parameters
start_time
[in] Starting time.
stop_time
[in] Stop time.
buffer
[in] Reference to the target array for data
Return Value
>=0 if successful, -1 in the case of error.
2817
Standard Library
Description
CiADX
CiADXWilder
CiBands
Bollinger Bands
CiEnvelopes
Envelopes
CiIchimoku
CiMA
Moving Average
CiSAR
CiStdDev
Standard Deviation
CiDEMA
CiTEMA
CiFrAMA
CiAMA
CiVIDyA
2818
Standard Library
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
MaPeriod
Create Methods
Create
Plus
Minus
Input/output
virtual Type
2819
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2820
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2821
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2822
Standard Library
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
2823
Standard Library
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
2824
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ADX for CiADX).
2825
Standard Library
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
MaPeriod
Create Methods
Create
Plus
Minus
Input/output
virtual Type
2826
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2827
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2828
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2829
Standard Library
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
2830
Standard Library
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
2831
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ADXW for CiADXWilder).
2832
Standard Library
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
MaPeriod
MaShift
Deviation
Applied
Create Methods
Create
Upper
Lower
Input/output
virtual Type
2833
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2834
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2835
Standard Library
Deviation
Returns the deviation.
double Deviation() const
Return Value
Returns the deviation, defined at the indicator creation.
2836
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2837
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
ma_shift,
// Shift
double
deviation,
// Deviation
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2838
Standard Library
Base
Returns the buffer element of the base line by the specified index.
double Base(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the Base line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
2839
Standard Library
Upper
Returns the buffer element of the upper line by the specified index.
double Upper(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2840
Standard Library
Lower
Returns the buffer element of the lower line by the specified index.
double Lower(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2841
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_BANDS for CiBands).
2842
Standard Library
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
MaPeriod
MaShift
MaMethod
Deviation
Applied
Create Methods
Create
Lower
Input/output
virtual Type
2843
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2844
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2845
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
2846
Standard Library
Deviation
Returns the value of deviation.
double Deviation() const
Return Value
Returns the value of deviation, defined at the indicator creation.
2847
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2848
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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,
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.
Return Value
true if successful, false if indicator hasn't been created.
2849
Standard Library
Upper
Returns the buffer element of the upper line by the specified index.
double Upper(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2850
Standard Library
Lower
Returns the buffer element of the lower line by the specified index.
double Lower(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2851
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ENVELOPES for CiEnvelopes).
2852
Standard Library
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
TenkanSenPeriod
KijunSenPeriod
SenkouSpanBPeriod
Create Methods
Create
KijunSen
SenkouSpanA
SenkouSpanB
ChinkouSpan
Input/output
virtual Type
2853
Standard Library
TenkanSenPeriod
Returns the TenkanSen period.
int TenkanSenPeriod() const
Return Value
Returns the TenkanSen period, defined at the indicator creation.
2854
Standard Library
KijunSenPeriod
Returns the KijunSen period.
int KijunSenPeriod() const
Return Value
Returns the KijunSen period, defined at the indicator creation.
2855
Standard Library
SenkouSpanBPeriod
Returns the SenkouSpanB period.
int SenkouSpanBPeriod() const
Return Value
Returns the SenkouSpanB period, defined at the indicator creation.
2856
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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.
Return Value
true if successful, false if indicator hasn't been created.
2857
Standard Library
TenkanSen
Returns the buffer element of the TenkanSen line by the specified index.
double TenkanSen(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the TenkanSen line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2858
Standard Library
KijunSen
Returns the buffer element of the KijunSen line by the specified index.
double KijunSen(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the KijunSen line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2859
Standard Library
SenkouSpanA
Returns the buffer element of the SenkouSpanA line by the specified index.
double SenkouSpanA(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the SenkouSpanA line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
2860
Standard Library
SenkouSpanB
Returns the buffer element of the SenkouSpanB line by the specified index.
double SenkouSpanB(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the SenkouSpanB line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
2861
Standard Library
ChinkouSpan
Returns the buffer element of the ChinkouSpan line by the specified index.
double ChinkouSpan(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the ChinkouSpan line of the specified index, or EMPTY_VALUE if there isn't
any correct data.
2862
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ICHIMOKU for CiIchimoku).
2863
Standard Library
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
MaPeriod
MaShift
MaMethod
Applied
Create Methods
Create
Input/output
virtual Type
2864
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2865
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2866
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator
creation.
2867
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2868
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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
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.
Return Value
true if successful, false if indicator hasn't been created.
2869
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2870
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_MA for CiMA).
2871
Standard Library
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
SarStep
Maximum
Create Methods
Create
Input/output
virtual Type
2872
Standard Library
SarStep
Returns the step of price increment (acceleration factor).
double SarStep() const
Return Value
The step of price increment, defined at the indicator creation.
2873
Standard Library
Maximum
Returns the maximum value of the step.
double Maximum() const
Return Value
The maximum value of the step, defined at the indicator creation.
2874
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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] Maximal stop level.
Return Value
true if successful, false if indicator hasn't been created.
2875
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2876
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Object type identifier (IND_SAR for CiSAR).
2877
Standard Library
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
MaPeriod
MaShift
MaMethod
Applied
Create Methods
Create
Input/output
virtual Type
2878
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2879
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2880
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator
creation.
2881
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2882
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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
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.
Return Value
true if successful, false if indicator hasn't been created.
2883
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2884
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_STDDEV for CiStdDev).
2885
Standard Library
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
MaPeriod
IndShift
Applied
Create Methods
Create
Input/output
virtual Type
2886
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2887
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2888
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2889
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
string,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
ind_shift,
// Shift
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2890
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2891
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_DEMA for CiDEMA).
2892
Standard Library
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
MaPeriod
IndShift
Applied
Create Methods
Create
Input/output
virtual Type
2893
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2894
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2895
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2896
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
ma_shift,
// Offset
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2897
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2898
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_TEMA for CiTEMA).
2899
Standard Library
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
MaPeriod
IndShift
Applied
Create Methods
Create
Input/output
virtual Type
2900
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2901
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2902
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2903
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
ma_shift,
// Offset
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2904
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2905
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_FRAMA for CiFrAMA).
2906
Standard Library
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
MaPeriod
FastEmaPeriod
SlowEmaPeriod
IndShift
Applied
Create Methods
Create
Input/output
virtual Type
2907
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2908
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Return Value
Returns the averaging period for the fast EMA, defined at the indicator creation.
2909
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Return Value
Returns the averaging period for the slow EMA, defined at the indicator creation.
2910
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2911
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2912
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
string,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
fast_ema_period,
int
slow_ema_period,
int
ind_shift,
// Shift
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2913
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2914
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_AMA for CiAMA).
2915
Standard Library
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
CmoPeriod
EmaPeriod
IndShift
Applied
Create Methods
Create
Input/output
virtual Type
2916
Standard Library
CmoPeriod
Returns the period for Momentum.
int CmoPeriod() const
Return Value
Returns the period for Momentum, defined at the indicator creation.
2917
Standard Library
EmaPeriod
Returns the averaging period for EMA.
int EmaPeriod() const
Return Value
Returns the averaging period for EMA, defined at the indicator creation.
2918
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Return Value
Returns the horizontal shift value, defined at the indicator creation.
2919
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2920
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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
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.
Return Value
true if successful, false if indicator hasn't been created.
2921
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2922
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_VIDYA for CiVIDyA).
2923
Standard Library
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
CiATR
CiBearsPower
Bears Power
CiBullsPower
Bulls Power
CiCCI
CiChaikin
Chaikin Oscillator
CiDeMarker
DeMarker
CiForce
Force Index
CiMACD
CiMomentum
Momentum
CiOsMA
CiRSI
CiRVI
CiStochastic
Stochastic Oscillator
CiWPR
CiTriX
2924
Standard Library
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
MaPeriod
Create Methods
Create
Input/output
virtual Type
2925
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2926
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2927
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2928
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ATR for CiATR).
2929
Standard Library
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
MaPeriod
Create Methods
Create
Input/output
virtual Type
2930
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2931
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2932
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2933
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_BEARS for CiBearsPower).
2934
Standard Library
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
MaPeriod
Create Methods
Create
Input/output
virtual Type
2935
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2936
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2937
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2938
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_BULLS for CiBullsPower).
2939
Standard Library
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
MaPeriod
Applied
Create Methods
Create
Input/output
virtual Type
2940
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2941
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2942
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Return Value
true if successful, false if indicator hasn't been created.
2943
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2944
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_CCI for CiCCI).
2945
Standard Library
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
FastMaPeriod
SlowMaPeriod
MaMethod
Applied
Create Methods
Create
Input/output
virtual Type
2946
Standard Library
FastMaPeriod
Returns the averaging period for the fast EMA.
int FastMaPeriod() const
Return Value
Returns the averaging period for the fast EMA, defined at the indicator creation.
2947
Standard Library
SlowMaPeriod
Returns the averaging period for the slow EMA.
int SlowMaPeriod() const
Return Value
Returns the averaging period for the slow EMA, defined at the indicator creation.
2948
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
2949
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
2950
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
int
fast_ma_period,
int
slow_ma_period,
ENUM_MA_METHOD
ma_method,
// Averaging method
ENUM_APPLIED_VOLUME applied
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).
Return Value
true if successful, false if indicator hasn't been created.
2951
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2952
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_CHAIKIN for CiChaikin).
2953
Standard Library
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
MaPeriod
Create Methods
Create
Input/output
virtual Type
2954
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2955
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2956
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2957
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_DEMARKER for CiDeMarker).
2958
Standard Library
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
MaPeriod
MaMethod
Applied
Create Methods
Create
Input/output
virtual Type
2959
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2960
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
2961
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
2962
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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
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).
Return Value
true if successful, false if indicator hasn't been created.
2963
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2964
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_FORCE for CiForce).
2965
Standard Library
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
FastEmaPeriod
SlowEmaPeriod
SignalPeriod
Applied
Create Methods
Create
Signal
Input/output
virtual Type
2966
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Return Value
Returns the averaging period for the fast EMA, defined at the indicator creation.
2967
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Return Value
Returns the averaging period for the slow EMA, defined at the indicator creation.
2968
Standard Library
SignalPeriod
Returns the averaging period for the signal line.
int SignalPeriod() const
Return Value
Returns the averaging period for the signal line, defined at the indicator creation.
2969
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2970
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
fast_ema_period,
int
slow_ema_period,
int
signal_period,
// Signal period
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2971
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2972
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2973
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_MACD for CiMACD).
2974
Standard Library
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
MaPeriod
Applied
Create Methods
Create
Input/output
virtual Type
2975
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2976
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2977
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Return Value
true if successful, false if indicator hasn't been created.
2978
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2979
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_MOMENTUM for CiMomentum).
2980
Standard Library
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
FastEmaPeriod
SlowEmaPeriod
SignalPeriod
Applied
Create Methods
Create
Input/output
virtual Type
2981
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Return Value
Returns the averaging period for the fast EMA, defined at the indicator creation.
2982
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Return Value
Returns the averaging period for the slow EMA, defined at the indicator creation.
2983
Standard Library
SignalPeriod
Returns the averaging period for the signal line.
int SignalPeriod() const
Return Value
Returns the averaging period for the signal line, defined at the indicator creation.
2984
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2985
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
fast_ema_period,
int
slow_ema_period,
int
signal_period,
int
applied
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.
Return Value
true if successful, false if indicator hasn't been created.
2986
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2987
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_OSMA for CiOsMA).
2988
Standard Library
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
MaPeriod
Applied
Create Methods
Create
Input/output
virtual Type
2989
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2990
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
2991
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type or handle to apply.
Return Value
true if successful, false if indicator hasn't been created.
2992
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2993
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Object type identifier (IND_RSI for CiRSI).
2994
Standard Library
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
MaPeriod
Create Methods
Create
Signal
Input/output
virtual Type
2995
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
2996
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Averaging period
ma_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
Return Value
true if successful, false if indicator hasn't been created.
2997
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
2998
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
2999
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_RVI for CiRVI).
3000
Standard Library
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
Kperiod
Dperiod
Slowing
MaMethod
PriceField
Create Methods
Create
Signal
Input/output
virtual Type
3001
Standard Library
Kperiod
Returns the averaging period for the %K line.
int Kperiod() const
Return Value
Returns the averaging period for the %K line, defined at the indicator creation.
3002
Standard Library
Dperiod
Returns the averaging period for the %D line.
int Dperiod() const
Return Value
Returns the averaging period for the %D line, defined at the indicator creation.
3003
Standard Library
Slowing
Returns the period of slowing.
int Slowing() const
Return Value
Returns the period of slowing, defined at the indicator creation.
3004
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
3005
Standard Library
PriceField
Returns the price type (Low/High or Close/Close) to apply.
ENUM_STO_PRICE PriceField() const
Return Value
The price type to apply, defined at the indicator creation.
3006
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
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
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).
Return Value
true if successful, false if indicator hasn't been created.
3007
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3008
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Signal
Returns the buffer element of the signal line by the specified index.
double Signal(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3009
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_STOCHASTIC for CiStochastic).
3010
Standard Library
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
MaPeriod
Applied
Create Methods
Create
Input/output
virtual Type
3011
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
3012
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
3013
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
ma_period,
// Averaging period
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
ma_period
[in] Averaging period.
applied
[in] Price type of handle to apply.
Return Value
true if successful, false if indicator hasn't been created.
3014
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3015
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_TRIX for CiTriX).
3016
Standard Library
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
CalcPeriod
Create Methods
Create
Input/output
virtual Type
3017
Standard Library
CalcPeriod
Returns the period for calculation.
int CalcPeriod() const
Return Value
Returns the period for calculation, defined at the indicator creation.
3018
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
// Calculation period
calc_period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
calc_period
[in] Period for calculation.
Return Value
true if successful, false if indicator hasn't been created.
3019
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3020
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_WPR for CiWPR).
3021
Standard Library
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
CiMFI
CiOBV
On Balance Volume
CiVolumes
Volumes
3022
Standard Library
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
Applied
Create Methods
Create
Input/output
virtual Type
3023
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
3024
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
ENUM_APPLIED_VOLUME applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3025
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3026
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_AD for CiAD).
3027
Standard Library
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
MaPeriod
Applied
Create Methods
Create
Input/output
virtual Type
3028
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Return Value
Returns the averaging period, defined at the indicator creation.
3029
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
3030
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
int
ma_period,
// Averaging period
ENUM_APPLIED_VOLUME applied
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).
Return Value
true if successful, false if indicator hasn't been created.
3031
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3032
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_MFI for CiMFI).
3033
Standard Library
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
Applied
Create Methods
Create
Input/output
virtual Type
3034
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
3035
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
ENUM_APPLIED_VOLUME applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3036
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3037
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_OBV for CiOBV).
3038
Standard Library
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
Applied
Create Methods
Create
Input/output
virtual Type
3039
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
3040
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
ENUM_APPLIED_VOLUME applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3041
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3042
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_VOLUMES for CiVolumes).
3043
Standard Library
Description
CiAC
Accelerator Oscillator
CiAlligator
Alligator
CiAO
Awesome Oscillator
CiFractals
Fractals
CiGator
Gator Oscillator
CiBWMFI
3044
Standard Library
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
Create
Input/output
virtual Type
3045
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// Symbol
// Period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3046
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3047
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_AC for CiAC).
3048
Standard Library
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
JawPeriod
JawShift
TeethPeriod
TeethShift
LipsPeriod
LipsShift
MaMethod
Applied
Create Methods
Create
Teeth
Lips
Input/output
virtual Type
3049
Standard Library
JawPeriod
Returns the averaging period for the Jaw line.
int JawPeriod() const
Return Value
Returns the averaging period for the Jaw line, defined at the indicator creation.
3050
Standard Library
JawShift
Returns the horizontal shift of the Jaws line.
int JawShift() const
Return Value
Horizontal shift of the Jaws line, defined at the indicator creation.
3051
Standard Library
TeethPeriod
Returns the averaging period for the Teeth line.
int TeethPeriod() const
Return Value
Returns the averaging period for the Teeth line, defined at the indicator creation.
3052
Standard Library
TeethShift
Returns the horizontal shift of the Teeth line.
int TeethShift() const
Return Value
Horizontal shift of the Teeth line, defined at the indicator creation.
3053
Standard Library
LipsPeriod
Returns the averaging period for the Lips line.
int LipsPeriod() const
Return Value
Returns the averaging period for the Lips line, defined at the indicator creation.
3054
Standard Library
LipsShift
Returns the horizontal shift of the Lips line.
int LipsShift() const
Return Value
Horizontal shift of the Lips line, defined at the indicator creation.
3055
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
3056
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
3057
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
jaw_period,
// Jaws period
int
jaw_shift,
// Jaws shift
int
teeth_period,
// Teeth period
int
teeth_shift,
// Teeth shift
int
lips_period,
// Lips period
int
lips_shift,
// Lips shift
ENUM_MA_METHOD
ma_method,
// Averaging method
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
jaw_period
[in] Jaws period.
jaw_shift
[in] Jaws shift.
teeth_period
[in] Teeth period.
teeth_shift
[in] Teeth 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.
Return Value
true if successful, false if indicator hasn't been created.
2000-2016, MetaQuotes Software Corp.
3058
Standard Library
Jaw
Returns the buffer element of the Jaws line by the specified index.
double Jaw(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the Jaws line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3059
Standard Library
Teeth
Returns the buffer element of the Teeth line by the specified index.
double Teeth(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the Teeth line of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3060
Standard Library
Lips
Returns the buffer element of the Lips line by the specified index.
double Lips(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the Lips line of the specified index, or EMPTY_VALUE if there isn't any correct
data.
3061
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_ALLIGATOR for CiAlligator).
3062
Standard Library
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
Create
Input/output
virtual Type
3063
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// Symbol
// Period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3064
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3065
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_AO for CiAO).
3066
Standard Library
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
Create
Lower
Input/output
virtual Type
3067
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
ENUM_TIMEFRAMES period
// Symbol
// Period
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3068
Standard Library
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3069
Standard Library
Lower
Returns the buffer element of the lower buffer by the specified index.
double Lower(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3070
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_FRACTALS for CiFractals).
3071
Standard Library
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
JawPeriod
JawShift
TeethPeriod
TeethShift
LipsPeriod
LipsShift
MaMethod
Applied
Create Methods
Create
Lower
Input/output
virtual Type
3072
Standard Library
JawPeriod
Returns the averaging period for the Jaws line.
int JawPeriod() const
Return Value
Returns the averaging period for the Jaws line, defined at the indicator creation.
3073
Standard Library
JawShift
Returns the horizontal shift of the Jaws line.
int JawShift() const
Return Value
Horizontal shift of the Jaws line, defined at the indicator creation.
3074
Standard Library
TeethPeriod
Returns the averaging period for the Teeth line.
int TeethPeriod() const
Return Value
Returns the averaging period for the Teeth line, defined at the indicator creation.
3075
Standard Library
TeethShift
Returns the horizontal shift of the Teeth line.
int TeethShift() const
Return Value
Horizontal shift of the Teeth line, defined at the indicator creation.
3076
Standard Library
LipsPeriod
Returns the averaging period for the Lips line.
int LipsPeriod() const
Return Value
Returns the averaging period for the Lips line, defined at the indicator creation.
3077
Standard Library
LipsShift
Returns the horizontal shift of the Lips line.
int LipsShift() const
Return Value
Horizontal shift of the Lips line, defined at the indicator creation.
3078
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Return Value
Returns the averaging method, defined at the indicator creation.
3079
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Return Value
Price type or handle to apply, defined at the indicator creation.
3080
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES period,
// Period
int
jaw_period,
// Jaws period
int
jaw_shift,
// Jaws shift
int
teeth_period,
// Teeth period
int
teeth_shift,
// Teeth shift
int
lips_period,
// Lips period
int
lips_shift,
// Lips shift
ENUM_MA_METHOD
ma_method,
// Averaging method
int
applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
jaw_period
[in] Jaws period.
jaw_shift
[in] Jaws shift.
teeth_period
[in] Teeth period.
teeth_shift
[in] Teeth 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.
Return Value
true if successful, false if indicator hasn't been created.
2000-2016, MetaQuotes Software Corp.
3081
Standard Library
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3082
Standard Library
Lower
Returns the buffer element of the lower buffer by the specified index.
double Upper(
int index
// Index
Parameters
index
[in] Element index.
Return Value
The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any
correct data.
3083
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_GATOR for CiGator).
3084
Standard Library
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
Applied
Create Methods
Create
Input/output
virtual Type
3085
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
Return Value
Volume type to apply, defined at the indicator creation.
3086
Standard Library
Create
It creates the indicator with specified parameters. Use Refresh() and GetData() to update and get the
indicator values.
bool Create(
string
symbol,
// Symbol
ENUM_TIMEFRAMES
period,
// Period
ENUM_APPLIED_VOLUME applied
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
applied
[in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration).
Return Value
true if successful, false if indicator hasn't been created.
3087
Standard Library
Main
Returns the buffer element by the specified index.
double Main(
int index
// Index
Parameters
index
[in] Element index.
Return Value
Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
3088
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_BWMFI for CiBWMFI).
3089
Standard Library
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
NumBuffers
NumParams
ParamType
ParamLong
ParamDouble
ParamString
Input/output
virtual Type
3090
Standard Library
NumBuffers
Sets the number of buffers.
bool NumBuffers(
int buffers
// number of buffers
Return Value
true if successful, false if buffers haven't been set.
3091
Standard Library
NumParams
Gets the number of parameters.
int NumParams() const
Return Value
Number of parameters, used in creation of the indicator.
3092
Standard Library
ParamType
Gets a type of the parameter with specified index.
ENUM_DATATYPE ParamType(
int index
// parameter index
) const
Parameters
index
[in] Parameter index.
Return Value
Returns the data type (value of ENUM_DATATYPE enumeration) of the parameter with specified
index, used in indicator creation.
Note
If parameter index is invalid, it returns WRONG_VALUE.
3093
Standard Library
ParamLong
Gets the value of specified parameter of long type.
long ParamLong(
int index
// index
) const
Parameters
index
[in] Parameter index.
Return Value
The value of specified parameter of long type, used in creation of the indicator.
Note
If the number is invalid, it returns 0.
3094
Standard Library
ParamDouble
Gets the value of specified parameter of double type.
double ParamDouble(
int index
// index
) const
Parameters
index
[in] Parameter index.
Return Value
The value of specified parameter of double type, used in creation of the indicator.
Note
If the number is invalid, it returns EMPTY_VALUE.
3095
Standard Library
ParamString
Gets the value of specified parameter of string type.
string ParamString(
int index
// index
) const
Parameters
index
[in] Parameter index.
Return Value
The value of specified string parameter, used in creation of the indicator.
Note
If the number is invalid, it returns an empty string.
3096
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
Return Value
Indicator type (IND_CUSTOM for CiCustom).
3097
Standard Library
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 (Expert Advisors).
MQL5 Standard Library (in terms of trade classes) is placed in the terminal working directory, in the
Include\Trade folder.
Class/Group
Description
CAccountInfo
CSymbolInfo
COrderInfo
CHistoryOrderInfo
CPositionInfo
CDealInfo
CTrade
CTerminalInfo
with
trade
instrument
of mql5
3098
Standard Library
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>
TradeMode
TradeModeDescription
Leverage
StopoutMode
StopoutModeDescription
TradeAllowed
TradeExpert
LimitOrders
MarginMode
MarginModeDescription
Credit
Profit
Equity
Margin
FreeMargin
MarginLevel
3099
Standard Library
MarginCall
MarginStopOut
Server
Currency
Company
InfoDouble
InfoString
Additional methods
OrderProfitCheck
MarginCheck
FreeMarginCheck
MaxLotCheck
on
the
3100
Standard Library
Login
Gets the account number.
long Login() const
Return Value
Account number.
3101
Standard Library
TradeMode
Gets the trade mode.
ENUM_ACCOUNT_TRADE_MODE TradeMode() const
Return Value
Trade mode (value of ENUM_ACCOUNT_TRADE_MODE enumeration).
3102
Standard Library
TradeModeDescription
Gets the trade mode as a string.
string TradeModeDescription() const
Return Value
Trade mode as a string.
3103
Standard Library
Leverage
Gets the amount of given leverage.
long Leverage() const
Return Value
Amount of given leverage.
3104
Standard Library
StopoutMode
Gets the mode of the Stop Out level specification.
ENUM_ACCOUNT_STOPOUT_MODE StopoutMode() const
Return Value
The stop out setting mode from the ENUM_ACCOUNT_STOPOUT_MODE enumeration.
3105
Standard Library
StopoutModeDescription
Gets the mode of the Stop Out level specification as a string.
string StopoutModeDescription() const
Return Value
The stop out setting mode as a string.
3106
Standard Library
TradeAllowed
Gets the flag of trade allowance.
bool TradeAllowed() const
Return Value
Flag of trade allowance.
3107
Standard Library
TradeExpert
Gets the flag of automated trade allowance.
bool TradeExpert() const
Return Value
Flag of automated trade allowance.
3108
Standard Library
LimitOrders
Gets the maximal number of allowed pending orders
int LimitOrders() const
Return Value
The maximal number of allowed pending orders.
Note
0 - no limits.
3109
Standard Library
Balance
Gets the balance of account.
double Balance() const
Return Value
The balance of account (in deposit currency).
3110
Standard Library
Credit
Gets the amount of given credit.
double Credit() const
Return Value
Amount of given credit (in deposit currency).
3111
Standard Library
Profit
Gets the amount of current profit on account.
double Profit() const
Return Value
Amount of current profit on account (in deposit currency).
3112
Standard Library
Equity
Gets the amount of current equity on account.
double Equity() const
Return Value
Amount of current equity on account (in deposit currency).
3113
Standard Library
Margin
Gets the amount of reserved margin.
double Margin() const
Return Value
Amount of reserved margin (in deposit currency).
3114
Standard Library
FreeMargin
Gets the amount of free margin.
double FreeMargin() const
Return Value
Amount of free margin (in deposit currency).
3115
Standard Library
MarginLevel
Gets the level of margin.
double MarginLevel() const
Return Value
Level of margin.
3116
Standard Library
MarginCall
Gets the level of margin for a deposit.
double MarginCall() const
Return Value
Level of margin for a deposit.
3117
Standard Library
MarginStopOut
Gets the level of margin for Stop Out.
double MarginStopOut() const
Return Value
Level of margin for Stop Out.
3118
Standard Library
Name
Gets the client name.
string Name() const
Return Value
Client name.
3119
Standard Library
Server
Gets the trade server name.
string Server() const
Return Value
Trade server name.
3120
Standard Library
Currency
Gets the deposit currency name.
string Currency() const
Return Value
Deposit currency name.
3121
Standard Library
Company
Gets the company name, that serves an account.
string Company() const
Return Value
Company name that serves an account.
3122
Standard Library
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
ENUM_ACCOUNT_INFO_INTEGER enumeration.
value
can
be
Return Value
Value of long type.
one
of
the
values
of
3123
Standard Library
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
ENUM_ACCOUNT_INFO_DOUBLE enumeration.
value
can
be
Return Value
Value of double type.
one
of
the
values
of
3124
Standard Library
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
ENUM_ACCOUNT_INFO_STRING enumeration.
value
can
be
Return Value
Value of string type.
one
of
the
values
of
3125
Standard Library
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,
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.
Return Value
If successful, it returns amount of profit or EMPTY_VALUE in the case of error.
3126
Standard Library
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.
Return Value
Amount of margin required for trade operation.
3127
Standard Library
FreeMarginCheck
Gets the amount of free margin left after trade operation.
double FreeMarginCheck(
const string
ENUM_ORDER_TYPE
symbol,
trade_operation,
// symbol
// 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.
Return Value
Amount of free margin left after trade operation.
3128
Standard Library
MaxLotCheck
Gets the maximum possible volume of trade operation.
double MaxLotCheck(
const string
symbol,
// symbol
ENUM_ORDER_TYPE
trade_operation,
// operation
double
price,
// price
double
percent=100
) 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.
percent=100
[in] Percent of available margin (0-100%), used for trade operation.
Return Value
Maximum possible volume of trade operation.
3129
Standard Library
MarginMode
Gets the margin calculation mode.
ENUM_ACCOUNT_MARGIN_MODE MarginMode() const
Return Value
The margin calculation mode from the ENUM_ACCOUNT_MARGIN_MODE enumeration-.
3130
Standard Library
MarginModeDescription
Gets the margin calculation mode as a string.
string MarginModeDescription() const
Return Value
Margin calculation mode as a string.
3131
Standard Library
CSymbolInfo
CSymbolInfo is a class for easy access to the symbol properties.
Description
CSymbolInfo class provides access to the symbol properties.
Declaration
class CSymbolInfo : public CObject
Title
#include <Trade\SymbolInfo.mqh>
RefreshRates
Properties
Name
Select
IsSynchronized
Volumes
Volume
VolumeHigh
VolumeLow
Miscellaneous
Time
Spread
SpreadFloat
TicksBookDepth
Levels
StopsLevel
FreezeLevel
Bid prices
3132
Standard Library
Bid
BidHigh
BidLow
Ask prices
Ask
AskHigh
AskLow
Prices
Last
LastHigh
LastLow
Trade modes
TradeCalcMode
TradeCalcModeDescription
TradeMode
TradeModeDescription
TradeExecution
TradeExecutionDescription
Swaps
SwapMode
SwapModeDescription
SwapRollover3days
SwapRollover3daysDescription
MarginMaintenance
MarginLong
MarginShort
MarginLimit
MarginStop
3133
Standard Library
orders
MarginStopLimit
TradeTimeFlags
TradeFillFlags
Quantization
Digits
Point
TickValue
TickValueProfit
TickValueLoss
TickSize
Contracts sizes
ContractSize
LotsMin
LotsMax
LotsStep
LotsLimit
Swaps sizes
SwapLong
SwapShort
Text properties
CurrencyBase
CurrencyProfit
CurrencyMargin
Bank
Description
Path
Symbol properties
SessionDeals
3134
Standard Library
SessionBuyOrders
SessionSellOrders
SessionTurnover
SessionInterest
SessionBuyOrdersVolume
SessionSellOrdersVolume
SessionOpen
SessionClose
SessionAW
SessionPriceSettlement
SessionPriceLimitMin
SessionPriceLimitMax
InfoDouble
InfoString
Service functions
NormalizePrice
3135
Standard Library
Refresh
Refreshes the symbol data.
void Refresh()
Return Value
None.
Note
The symbol should be selected by Name method.
3136
Standard Library
RefreshRates
Refreshes the symbol quotes data.
bool RefreshRates()
Return Value
true in case of success, false if unable to refresh quotes.
Note
The symbol should be selected by Name method.
3137
Standard Library
Name
Gets symbol name.
string Name() const
Return Value
Symbol name.
Name
Sets symbol name.
bool Name(string name)
Return Value
None.
3138
Standard Library
Select
Gets the "Market Watch" symbol flag.
bool Select() const
Return Value
"Market Watch" symbol flag.
Select
Sets the "Market Watch" symbol flag.
bool Select()
Return Value
true in case of success, false if unable to change flag.
3139
Standard Library
IsSynchronized
Checks the symbol synchronization with server.
bool IsSynchronized() const
Return Value
true if the symbol is synchronized with server, false if not.
Note
The symbol should be selected by Name method.
3140
Standard Library
Volume
Gets the volume of last deal.
long Volume() const
Return Value
Volume of last deal.
Note
The symbol should be selected by Name method.
3141
Standard Library
VolumeHigh
Gets the maximal volume of the day.
long VolumeHigh() const
Return Value
Maximal volume of the day.
Note
The symbol should be selected by Name method.
3142
Standard Library
VolumeLow
Gets the minimal volume of the day.
long VolumeLow() const
Return Value
Minimal volume of the day.
Note
The symbol should be selected by Name method.
3143
Standard Library
Time
Gets the time of last quote.
datetime Time() const
Return Value
Time of last quote.
Note
The symbol should be selected by Name method.
3144
Standard Library
Spread
Gets the amount of spread (in points).
int Spread() const
Return Value
Gets the amount of spread (in points).
Note
The symbol should be selected by Name method.
3145
Standard Library
SpreadFloat
Gets the flag of floating spread.
bool SpreadFloat() const
Return Value
Flag of floating spread.
Note
The symbol should be selected by Name method.
3146
Standard Library
TicksBookDepth
Gets the depth of ticks saving.
int TicksBookDepth() const
Return Value
Depth of ticks saving.
Note
The symbol should be selected by Name method.
3147
Standard Library
StopsLevel
Gets the minimal stop level for orders (in points).
int StopsLevel() const
Return Value
Minimal stop level for orders (in points).
Note
The symbol should be selected by Name method.
3148
Standard Library
FreezeLevel
Gets the freeze level (in points).
int FreezeLevel() const
Return Value
Distance of freeze level (in points).
Note
The symbol should be selected by Name method.
3149
Standard Library
Bid
Gets the current Bid price.
double Bid() const
Return Value
Current Bid price.
Note
The symbol should be selected by Name method.
3150
Standard Library
BidHigh
Gets the maximal Bid price of the day.
double BidHigh() const
Return Value
Maximal Bid price of the day.
Note
The symbol should be selected by Name method.
3151
Standard Library
BidLow
Gets the minimal Bid price of the day.
double BidLow() const
Return Value
Minimal Bid price of the day.
Note
The symbol should be selected by Name method.
3152
Standard Library
Ask
Gets the current Ask price.
double Ask() const
Return Value
Current Ask price.
Note
The symbol should be selected by Name method.
3153
Standard Library
AskHigh
Gets the maximal Ask price for a day.
double AskHigh() const
Return Value
Maximal Ask price of the day.
Note
The symbol should be selected by Name method.
3154
Standard Library
AskLow
Gets the minimal Ask price for a day.
double AskLow() const
Return Value
Minimal Ask price of the day.
Note
The symbol should be selected by Name method.
3155
Standard Library
Last
Gets the current Last price.
double Last() const
Return Value
Current Last price.
3156
Standard Library
LastHigh
Gets the maximal Last price of the day.
double LastHigh() const
Return Value
Maximal Last price of the day.
Note
The symbol should be selected by Name method.
3157
Standard Library
LastLow
Gets the minimal Last price of the day.
double LastLow() const
Return Value
Minimal Last price of the day.
Note
The symbol should be selected by Name method.
3158
Standard Library
TradeCalcMode
Gets the mode of contract cost calculation.
ENUM_SYMBOL_CALC_MODE TradeCalcMode() const
Return Value
Mode of contract cost calculation (value of ENUM_SYMBOL_CALC_MODE enumeration).
Note
The symbol should be selected by Name method.
3159
Standard Library
TradeCalcModeDescription
Gets the mode of contract cost calculation as a string.
string TradeCalcModeDescription() const
Return Value
Mode of contract cost calculation as a string.
Note
The symbol should be selected by Name method.
3160
Standard Library
TradeMode
Gets the order execution type.
ENUM_SYMBOL_TRADE_MODE TradeMode() const
Return Value
Order execution type (value of ENUM_SYMBOL_TRADE_MODE enumeration).
Note
The symbol should be selected by Name method.
3161
Standard Library
TradeModeDescription
Gets the trade mode as a string.
string TradeModeDescription() const
Return Value
Trade mode as a string.
Note
The symbol should be selected by Name method.
3162
Standard Library
TradeExecution
Gets the trade execution mode.
ENUM_SYMBOL_TRADE_EXECUTION TradeExecution() const
Return Value
Trade execution mode (value of ENUM_SYMBOL_TRADE_EXECUTION enumeration).
Note
The symbol should be selected by Name method.
3163
Standard Library
TradeExecutionDescription
Gets the description of trade execution mode as a string.
string TradeExecutionDescription() const
Return Value
Trade execution mode as a string.
Note
The symbol should be selected by Name method.
3164
Standard Library
SwapMode
Gets the swap calculation mode.
ENUM_SYMBOL_SWAP_MODE SwapMode() const
Return Value
Swap calculation mode (value of ENUM_SYMBOL_SWAP_MODE enumeration).
Note
The symbol should be selected by Name method.
3165
Standard Library
SwapModeDescription
Gets the swap mode description as a string.
string SwapModeDescription() const
Return Value
Swap mode descriprion as a string.
Note
The symbol should be selected by Name method.
3166
Standard Library
SwapRollover3days
Gets the swap rollover day.
ENUM_DAY_OF_WEEK SwapRollover3days() const
Return Value
Swap rollover day (value of ENUM_DAY_OF_WEEK enumeration).
Note
The symbol should be selected by Name method.
3167
Standard Library
SwapRollover3daysDescription
Gets the swap rollover day as a string.
string SwapRollover3daysDescription() const
Return Value
Swap rollover day as a string.
Note
The symbol should be selected by Name method.
3168
Standard Library
MarginInitial
Gets the value of initial margin.
double MarginInitial()
Return Value
Value of initial margin.
Note
It returns 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.
The symbol should be selected by Name method.
3169
Standard Library
MarginMaintenance
Gets the value of maintenance margin.
double MarginMaintenance()
Return Value
Value of maintenance margin.
Note
It returns 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.
The symbol should be selected by Name method.
3170
Standard Library
MarginLong
Gets the rate of margin charging on long positons.
double MarginLong() const
Return Value
Rate of margin charging on long positons.
Note
The symbol should be selected by Name method.
3171
Standard Library
MarginShort
Gets the rate of margin charging on short positons.
double MarginShort() const
Return Value
Rate of margin charging on short positons.
Note
The symbol should be selected by Name method.
3172
Standard Library
MarginLimit
Gets the rate of margin charging on Limit orders.
double MarginLimit() const
Return Value
Rate of margin charging on Limit orders.
Note
The symbol should be selected by Name method.
3173
Standard Library
MarginStop
Gets the rate of margin charging on Stop orders.
double MarginStop() const
Return Value
Rate of margin charging on Stop orders.
Note
The symbol should be selected by Name method.
3174
Standard Library
MarginStopLimit
Gets the rate of margin charging on Stop Limit orders.
double MarginStopLimit() const
Return Value
Rate of margin charging on Stop Limit orders.
Note
The symbol should be selected by Name method.
3175
Standard Library
TradeTimeFlags
Gets the flags of allowed expiration modes.
int TradeTimeFlags() const
Return Value
Flags of allowed expiration modes.
Note
The symbol should be selected by Name method.
3176
Standard Library
TradeFillFlags
Gets the flags of allowed filling modes.
int TradeFillFlags() const
Return Value
Flags of allowed filling modes.
Note
The symbol should be selected by Name method.
3177
Standard Library
Digits
Gets the number of digits after period.
int Digits() const
Return Value
The number of digits after period.
Note
The symbol should be selected by Name method.
3178
Standard Library
Point
Gets the value of one point.
double Point() const
Return Value
Value of one point.
Note
The symbol should be selected by Name method.
3179
Standard Library
TickValue
Gets the tick value (minimal change of price).
double TickValue() const
Return Value
Tick value (minimal change of price).
Note
The symbol should be selected by Name method.
3180
Standard Library
TickValueProfit
Gets the calculated tick price for a profitable position.
double TickValueProfit() const
Return Value
The calculated tick price for a profitable position.
Note
The symbol should be selected by Name method.
3181
Standard Library
TickValueLoss
Gets the calculated tick price for a losing position.
double TickValueLoss() const
Return Value
The calculated tick price for a losing position.
Note
The symbol should be selected by Name method.
3182
Standard Library
TickSize
Gets the minimal change of price.
double TickSize() const
Return Value
Minimal change of price.
Note
The symbol should be selected by Name method.
3183
Standard Library
ContractSize
Gets the amount of trade contract.
double ContractSize() const
Return Value
Amount of trade contract.
Note
The symbol should be selected by Name method.
3184
Standard Library
LotsMin
Gets the minimal volume to close a deal.
double LotsMin() const
Return Value
Minimal volume to close a deal.
Note
The symbol should be selected by Name method.
3185
Standard Library
LotsMax
Gets the maximal volume to close a deal.
double LotsMax() const
Return Value
Maximal volume to close a deal.
Note
The symbol should be selected by Name method.
3186
Standard Library
LotsStep
Gets the minimal step of volume change to close a deal.
double LotsStep() const
Return Value
Minimal step of volume change to close a deal.
Note
The symbol should be selected by Name method.
3187
Standard Library
LotsLimit
Gets the maximal allowed volume of opened position and pending orders (direction insensitive) for one
symbol.
double LotsLimit() const
Return Value
The maximal allowed volume of opened position and pending orders (direction insensitive) for one
symbol.
Note
The symbol should be selected by Name method.
3188
Standard Library
SwapLong
Gets the value of long position swap.
double SwapLong() const
Return Value
Value of long position swap.
Note
The symbol should be selected by Name method.
3189
Standard Library
SwapShort
Gets the value of short position swap.
double SwapShort() const
Return Value
Value of short position swap.
Note
The symbol should be selected by Name method.
3190
Standard Library
CurrencyBase
Gets the name of symbol base currency.
string CurrencyBase() const
Return Value
Name of symbol base currency.
Note
The symbol should be selected by Name method.
3191
Standard Library
CurrencyProfit
Gets the profit currency name.
string CurrencyProfit() const
Return Value
Profit currency name.
Note
The symbol should be selected by Name method.
3192
Standard Library
CurrencyMargin
Gets the margin currency name.
string CurrencyMargin() const
Return Value
Margin currency name.
Note
The symbol should be selected by Name method.
3193
Standard Library
Bank
Gets the name of current quote source.
string Bank() const
Return Value
Name of current quote source.
Note
The symbol should be selected by Name method.
3194
Standard Library
Description
Gets the string description of symbol.
string Description() const
Return Value
String description of symbol.
Note
The symbol should be selected by Name method.
3195
Standard Library
Path
Gets the path in symbols tree.
string Path() const
Return Value
Gets the path in symbols tree.
Note
The symbol should be selected by Name method.
3196
Standard Library
SessionDeals
Gets the number of deals in the current session.
long SessionDeals() const
Return Value
Number of deals in the current session.
Note
The symbol should be selected by Name method.
3197
Standard Library
SessionBuyOrders
Gets the number of Buy orders at the moment.
long SessionBuyOrders() const
Return Value
Number of Buy orders at the moment.
Note
The symbol should be selected by Name method.
3198
Standard Library
SessionSellOrders
Gets then number of Sell orders at the moment.
long SessionSellOrders() const
Return Value
Number of Sell orders at the moment.
Note
The symbol should be selected by Name method.
3199
Standard Library
SessionTurnover
Gets summary turnover of the current session.
double SessionTurnover() const
Return Value
Summary turnover of the current session.
Note
The symbol should be selected by Name method.
3200
Standard Library
SessionInterest
Gets the summary of open interest of the current session.
double SessionInterest() const
Return Value
Summary open interest of the current session.
Note
The symbol should be selected by Name method.
3201
Standard Library
SessionBuyOrdersVolume
Gets the current volume of Buy orders.
double SessionBuyOrdersVolume() const
Return Value
Current volume of Buy orders.
Note
The symbol should be selected by Name method.
3202
Standard Library
SessionSellOrdersVolume
Gets the current volume of Sell orders.
double SessionSellOrdersVolume() const
Return Value
Current volume of Sell orders.
Note
The symbol should be selected by Name method.
3203
Standard Library
SessionOpen
Gets the open price of the current session.
double SessionOpen() const
Return Value
Open price of the current session.
Note
The symbol should be selected by Name method.
3204
Standard Library
SessionClose
Gets the close price of the current session.
double SessionClose() const
Return Value
Close price of the current session.
Note
The symbol should be selected by Name method.
3205
Standard Library
SessionAW
Gets the average weighted price of the current session.
double SessionAW() const
Return Value
Average weighted price of the current session.
Note
The symbol should be selected by Name method.
3206
Standard Library
SessionPriceSettlement
Gets the settlement price of the current session.
double SessionPriceSettlement() const
Return Value
Settlement price of the current session.
Note
The symbol should be selected by Name method.
3207
Standard Library
SessionPriceLimitMin
Gets the minimal price of the current session.
double SessionPriceLimitMin() const
Return Value
Minimal price of the current session.
Note
The symbol should be selected by Name method.
3208
Standard Library
SessionPriceLimitMax
Gets the maximal price of the current session.
double SessionPriceLimitMax() const
Return Value
Maximal price of the current session.
Note
The symbol should be selected by Name method.
3209
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_SYMBOL_INFO_INTEGER prop_id,
// property ID
long&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The symbol should be selected by Name method.
3210
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_SYMBOL_INFO_DOUBLE prop_id,
// property ID
double&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The symbol should be selected by Name method.
3211
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_SYMBOL_INFO_STRING prop_id,
// property ID
string&
// reference to variable
var
) const
Parameters
prop_id
[in] ID of text property.
var
[out] Reference to string type variable to place result.
Return Value
true in case of success, false if unable to get property value.
Note
The symbol should be selected by Name method.
3212
Standard Library
NormalizePrice
Returns the value of price, normalized using the symbol properties.
double NormalizePrice(
double
price
// price
) const
Parameters
price
[in] Price.
Return Value
Normalized price.
Note
The symbol should be selected by Name method.
3213
Standard Library
COrderInfo
COrderInfo is a class for easy access to the pending order properties.
Description
COrderInfo class provides access to the pending order properties.
Declaration
class COrderInfo : public CObject
Title
#include <Trade\OrderInfo.mqh>
TimeSetup
TimeSetupMsc
OrderType
OrderTypeDescription
State
StateDescription
TimeExpiration
TimeDone
TimeDoneMsc
TypeFilling
TypeFillingDescription
TypeTime
TypeTimeDescription
Magic
PositionId
3214
Standard Library
VolumeCurrent
PriceOpen
StopLoss
TakeProfit
PriceCurrent
PriceStopLimit
Comment
InfoDouble
InfoString
State
StoreState
CheckState
Selection
Select
SelectByIndex
3215
Standard Library
Ticket
Gets the ticket of an order, previously selected for access using the Select method.
ulong Ticket() const
Return Value
Order ticket if successful, otherwise - ULONG_MAX.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3216
Standard Library
TimeSetup
Gets the time of order placement.
datetime TimeSetup() const
Return Value
Time of order placement.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3217
Standard Library
TimeSetupMsc
Receives the time of placing an order for execution in milliseconds since 01.01.1970.
ulong TimeSetupMsc() const
Return Value
The time of placing an order for execution in milliseconds since 01.01.1970.
Note
Order should be preliminarily selected for access using Select (by ticket) or SelectByIndex (by index)
method.
3218
Standard Library
OrderType
Gets the order type.
ENUM_ORDER_TYPE OrderType()
Return Value
Order type (value of ENUM_ORDER_TYPE enumeration).
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3219
Standard Library
TypeDescription
Gets the order type as a string.
string TypeDescription() const
Return Value
Order type as a string.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3220
Standard Library
State
Gets the order state.
ENUM_ORDER_STATE State() const
Return Value
Order state (value of ENUM_ORDER_STATE enumeration).
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3221
Standard Library
StateDescription
Gets the order state as a string.
string StateDescription() const
Return Value
Order state as a string.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3222
Standard Library
TimeExpiration
Gets the order expiration time.
datetime TimeExpiration() const
Return Value
Order expiration time, set on its placement.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3223
Standard Library
TimeDone
Gets the time of order execution or cancellation.
datetime TimeDone() const
Return Value
Time of order execution or cancellation.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3224
Standard Library
TimeDoneMsc
Receives order execution or cancellation time in milliseconds since 01.01.1970.
ulong TimeDoneMsc() const
Return Value
Order execution or cancellation time in milliseconds since 01.01.1970.
Note
Order should be preliminarily selected for access using Select (by ticket) or SelectByIndex (by index)
method.
3225
Standard Library
TypeFilling
Gets the order filling type.
ENUM_ORDER_TYPE_FILLING TypeFilling() const
Return Value
Order filling type (value of ENUM_ORDER_TYPE_FILLING enumeration).
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3226
Standard Library
TypeFillingDescription
Gets the order filling type as a string.
string TypeFillingDescription() const
Return Value
Order filling type as a string.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3227
Standard Library
TypeTime
Gets the type of order at the time of the expiration.
ENUM_ORDER_TYPE_TIME TypeTime() const
Return Value
Type of order at the time of the expiration.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3228
Standard Library
TypeTimeDescription
Gets the order type by expiration time as a string.
string TypeTimeDescription() const
Return Value
Order type by expiration time as a string.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3229
Standard Library
Magic
Gets the ID of expert that placed the order.
long Magic() const
Return Value
ID of expert that placed the order.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3230
Standard Library
PositionId
Gets the ID of position.
long PositionId() const
Return Value
ID of position, in which the order was involved.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3231
Standard Library
VolumeInitial
Gets the initial volume of order.
double VolumeInitial() const
Return Value
Initial volume of order.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3232
Standard Library
VolumeCurrent
Gets the unfilled volume of order.
double VolumeCurrent() const
Return Value
Unfilled volume of order.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3233
Standard Library
PriceOpen
Gets the order price.
double PriceOpen() const
Return Value
Price of order placement.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3234
Standard Library
StopLoss
Gets the order's Stop Loss.
double StopLoss() const
Return Value
Order's Stop Loss.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3235
Standard Library
TakeProfit
Gets the order's Take Profit.
double TakeProfit() const
Return Value
Order's Take Profit.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3236
Standard Library
PriceCurrent
Gets the current price by order symbol.
double PriceCurrent() const
Return Value
Current price by order symbol.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3237
Standard Library
PriceStopLimit
Gets the price of a Limit order.
double PriceStopLimit() const
Return Value
Price of setting limit order.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3238
Standard Library
Symbol
Gets the name of order symbol.
string Symbol() const
Return Value
Name of order symbol.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3239
Standard Library
Comment
Gets the order comment.
string Comment() const
Return Value
Order comment.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3240
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_ORDER_PROPERTY_INTEGER prop_id,
// property ID
long&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3241
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_ORDER_PROPERTY_DOUBLE prop_id,
// property ID
double&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3242
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_ORDER_PROPERTY_STRING prop_id,
// property ID
string&
// reference to variable
var
) const
Parameters
prop_id
[in] ID of text property.
var
[out] Reference to string type variable to place result.
Return Value
true in case of success, false if unable to get property value.
Note
The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3243
Standard Library
StoreState
Saves the order parameters.
void StoreState()
Return Value
None.
3244
Standard Library
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Return Value
true - if the order parameters have changed since the last call of the StoreState() method, otherwise
- false.
3245
Standard Library
Select
Selects an order by ticket for further access to its properties.
bool Select(
ulong
ticket
// order ticket
Return Value
true in case of success, false if unable to select order.
3246
Standard Library
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex(
int
index
// order index
Return Value
true in case of success, false if unable to select order.
3247
Standard Library
CHistoryOrderInfo
CHistoryOrderInfo is a class for easy access to the history order properties.
Description
CHistoryOrderInfo class provides easy access to the history order properties.
Declaration
class CHistoryOrderInfo : public CObject
Title
#include <Trade\HistoryOrderInfo.mqh>
TimeSetupMsc
OrderType
OrderTypeDescription
State
StateDescription
TimeExpiration
TimeDone
TimeDoneMsc
TypeFilling
TypeFillingDescription
TypeTime
TypeTimeDescription
Magic
PositionId
3248
Standard Library
VolumeCurrent
PriceOpen
StopLoss
TakeProfit
PriceCurrent
PriceStopLimit
Comment
InfoDouble
InfoString
Selection
Ticket
SelectByIndex
3249
Standard Library
TimeSetup
Gets the time of order placement.
datetime TimeSetup() const
Return Value
Time of order placement.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3250
Standard Library
TimeSetupMsc
Receives the time of placing an order for execution in milliseconds since 01.01.1970.
ulong TimeSetupMsc() const
Return Value
The time of placing an order for execution in milliseconds since 01.01.1970.
Note
Historical order should be preliminarily selected for access using Ticket (by ticket) or SelectByIndex (by
index) method.
3251
Standard Library
OrderType
Gets the order type.
ENUM_ORDER_TYPE OrderType() const
Return Value
Order type (value of ENUM_ORDER_TYPE enumeration).
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3252
Standard Library
TypeDescription
Gets the order type as a string.
string TypeDescription() const
Return Value
Order type as a string.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3253
Standard Library
State
Gets the order state.
ENUM_ORDER_STATE State() const
Return Value
Order state (value of ENUM_ORDER_STATE enumeration).
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3254
Standard Library
StateDescription
Gets the order state as a string.
string StateDescription() const
Return Value
Order state as a string.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3255
Standard Library
TimeExpiration
Gets the time of order expiration.
datetime TimeExpiration() const
Return Value
Time of order expiration, set on its placement.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3256
Standard Library
TimeDone
Gets the time of order execution or cancellation.
datetime TimeDone() const
Return Value
Time of order execution or cancellation.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3257
Standard Library
TimeDoneMsc
Receives order execution or cancellation time in milliseconds since 01.01.1970.
ulong TimeDoneMsc() const
Return Value
Order execution or cancellation time in milliseconds since 01.01.1970.
Note
Historical order should be preliminarily selected for access using Ticket (by ticket) or SelectByIndex (by
index) method.
3258
Standard Library
TypeFilling
Gets the type of order execution by remainder.
ENUM_ORDER_TYPE_FILLING TypeFilling() const
Return Value
Type of order execution by remainder (value of ENUM_ORDER_TYPE_FILLING enumeration).
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3259
Standard Library
TypeFillingDescription
Gets the type of order execution by remainder as a string.
string TypeFillingDescription() const
Return Value
Type order of execution by remainder as a string.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3260
Standard Library
TypeTime
Gets the type of order at the time of the expiration.
ENUM_ORDER_TYPE_TIME TypeTime() const
Return Value
Type of order at the time of the expiration (value of ENUM_ORDER_TYPE_TIME enumeration).
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3261
Standard Library
TypeTimeDescription
Gets the order type by expiration time as a string.
string TypeTimeDescription() const
Return Value
Order type by expiration time as a string.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3262
Standard Library
Magic
Gets the ID of the Expert Advisor, that placed the order.
long Magic() const
Return Value
ID of the Expert Advisor, that placed the order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3263
Standard Library
PositionId
Gets the ID of position.
long PositionId() const
Return Value
ID of position, in which the order was involved.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3264
Standard Library
VolumeInitial
Gets the initial volume of order.
double VolumeInitial() const
Return Value
Initial volume of order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3265
Standard Library
VolumeCurrent
Gets the unfilled volume of order.
double VolumeCurrent() const
Return Value
Unfilled volume of order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3266
Standard Library
PriceOpen
Gets the order price.
double PriceOpen() const
Return Value
Price of order placement.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3267
Standard Library
StopLoss
Gets the Stop Loss price of the order.
double StopLoss() const
Return Value
Stop Loss price of the order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3268
Standard Library
TakeProfit
Gets the Take Profit price of the order.
double TakeProfit() const
Return Value
The Take Profit price of the order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3269
Standard Library
PriceCurrent
Gets the current price of the order's symbol.
double PriceCurrent() const
Return Value
The current price of order's symbol.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3270
Standard Library
PriceStopLimit
Gets the stop limit price of the order.
double PriceStopLimit() const
Return Value
Stop Limit price of the order.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3271
Standard Library
Symbol
Gets the name of order symbol.
string Symbol() const
Return Value
Name of order symbol.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3272
Standard Library
Comment
Gets the order comment.
string Comment() const
Return Value
Order comment.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3273
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_ORDER_PROPERTY_INTEGER prop_id,
// property ID
long&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3274
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_ORDER_PROPERTY_DOUBLE prop_id,
// property ID
double&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3275
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_ORDER_PROPERTY_STRING prop_id,
// property ID
string&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index)
methods.
3276
Standard Library
Return Value
Order ticket.
// order ticket
Parameters
ticket
[in] Order ticket.
3277
Standard Library
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex(
int
index
// order index
Return Value
true in case of success, false if unable to select order.
3278
Standard Library
CPositionInfo
CPositionInfo is a class for easy access to the open position properties.
Description
CPositionInfo class provides easy access to the open position properties.
Declaration
class CPositionInfo : public CObject
Title
#include <Trade\PositionInfo.mqh>
TimeMsc
TimeUpdate
TimeUpdateMsc
PositionType
TypeDescription
Magic
Identifier
PriceOpen
StopLoss
TakeProfit
PriceCurrent
Commission
Swap
Profit
3279
Standard Library
Symbol
Comment
InfoDouble
InfoString
Selection
Select
SelectByIndex
SelectByMagic
SelectByTicket
State
StoreState
CheckState
3280
Standard Library
Time
Gets the time of position opening.
datetime Time() const
Return Value
Time of position opening.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3281
Standard Library
TimeMsc
Receives position opening time in milliseconds since 01.01.1970.
ulong TimeMsc() const
Return Value
Position opening time in milliseconds since 01.01.1970.
Note
Position should be preliminarily selected for access using Select (by symbol) or SelectByIndex (by index)
method.
3282
Standard Library
TimeUpdate
Receives the time of position changing in seconds since 01.01.1970.
datetime TimeUpdate() const
Return Value
Time of position changing in seconds since 01.01.1970.
Note
Position should be preliminarily selected for access using Select (by symbol) or SelectByIndex (by index)
method.
3283
Standard Library
TimeUpdateMsc
Receives the time of position changing in milliseconds since 01.01.1970.
ulong TimeUpdateMsc() const
Return Value
The time of position changing in milliseconds since 01.01.1970.
Note
Position should be preliminarily selected for access using Select (by symbol) or SelectByIndex (by index)
method.
3284
Standard Library
PositionType
Gets the position type.
ENUM_POSITION_TYPE PositionType() const
Return Value
Position type (value of ENUM_POSITION_TYPE enumeration).
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3285
Standard Library
TypeDescription
Gets the position type as a string.
string TypeDescription() const
Return Value
Position type as a string.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3286
Standard Library
Magic
Gets the ID of Expert Advisor that opened the position.
long Magic() const
Return Value
ID of the Expert Advisor that opened the position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3287
Standard Library
Identifier
Gets the ID of position.
long Identifier() const
Return Value
ID of position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3288
Standard Library
Volume
Gets the volume of position.
double Volume() const
Return Value
Volume of position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3289
Standard Library
PriceOpen
Gets the price of position opening.
double PriceOpen() const
Return Value
Position open price.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3290
Standard Library
StopLoss
Gets the Stop Loss price of the position.
double StopLoss() const
Return Value
The Stop Loss price of the position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3291
Standard Library
TakeProfit
Gets the Take Profit price of the position.
double TakeProfit() const
Return Value
The Take Profit price of the position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3292
Standard Library
PriceCurrent
Gets the current price by position symbol.
double PriceCurrent() const
Return Value
Current price by position symbol.
3293
Standard Library
Commission
Gets the amount of commission of the position.
double Commission() const
Return Value
Amount of commission of the position (in deposit currency).
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3294
Standard Library
Swap
Gets the amount of swap of the position.
double Swap() const
Return Value
Amount of swap of the position (in deposit currency).
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3295
Standard Library
Profit
Gets the amount of current profit of the position.
double Profit() const
Return Value
Amount of current profit of the position (in deposit currency).
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3296
Standard Library
Symbol
Gets the name of position symbol.
string Symbol() const
Return Value
Name of position symbol.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3297
Standard Library
Comment
Gets the comment of the position.
string Comment() const
Return Value
Comment of the position.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3298
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_POSITION_PROPERTY_INTEGER prop_id,
// property ID
long&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3299
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_POSITION_PROPERTY_DOUBLE prop_id,
// property ID
double&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3300
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_POSITION_PROPERTY_STRING prop_id,
// property ID
string&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
3301
Standard Library
Select
Select the position for further work.
bool Select(
const string symbol
// symbol
Parameters
symbol
[in] Symbol for position selection.
3302
Standard Library
SelectByIndex
Selects the position by index for further access to its properties.
bool SelectByIndex(
int
index
// position index
Return Value
true in case of success, false if unable to select position.
3303
Standard Library
SelectByMagic
Select a position based in the name of a financial instrument and magic number to further work with.
bool SelectByIndex(
const string symbol,// Symbol name
const ulong
magic
// Magic number
Parameters
symbol
[in] Symbol name.
magic
[in] Magic number of the position.
Return Value
Returns true if successful or false if position selection failed.
3304
Standard Library
SelectByTicket
Selects position by ticket for further operation.
bool SelectByTicket(
ulong ticket
// position ticket
Parameters
ticket
[in] Position ticket.
Return value
true - success, false - no position selected.
3305
Standard Library
StoreState
Saves the position parameters.
void StoreState()
Return Value
None.
3306
Standard Library
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Return Value
true - if the position parameters have changed since the last call of the StoreState() method,
otherwise - false.
3307
Standard Library
CDealInfo
CDealInfo is a class for easy access to the deal properties.
Description
CDealInfo class provides access to the deal properties.
Declaration
class CDealInfo : public CObject
Title
#include <Trade\DealInfo.mqh>
Time
TimeMsc
DealType
TypeDescription
Entry
EntryDescription
Magic
PositionId
Price
Commision
Swap
Profit
Comment
3308
Standard Library
InfoDouble
InfoString
Selection
Ticket
SelectByIndex
3309
Standard Library
Order
Gets the order by which the deal is executed.
long Order() const
Return Value
Order by which the deal is executed.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3310
Standard Library
Time
Gets the time of deal execution.
datetime Time() const
Return Value
Time of deal execution.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3311
Standard Library
TimeMsc
Receives the time of a deal execution in milliseconds since 01.01.1970.
ulong TimeMsc() const
Return Value
The time of a deal execution in milliseconds since 01.01.1970.
Note
Deal should be preliminarily selected for access using Ticket (by ticket) or SelectByIndex (by index)
method.
3312
Standard Library
DealType
Gets the deal type.
ENUM_DEAL_TYPE DealType() const
Return Value
Deal type (value of ENUM_DEAL_TYPE enumeration).
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3313
Standard Library
TypeDescription
Gets the deal type as a string.
string TypeDescription() const
Return Value
Deal type as a string.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3314
Standard Library
Entry
Gets the deal direction.
ENUM_DEAL_ENTRY Entry() const
Return Value
Deal direction (value of ENUM_DEAL_ENTRY enumeration.).
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3315
Standard Library
EntryDescription
Gets the deal direction as a string.
string EntryDescription() const
Return Value
Deal direction as a string.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3316
Standard Library
Magic
Gets the ID of the Expert Advisor, that executed the deal.
long Magic() const
Return Value
ID of the Expert Advisor, that executed the deal.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3317
Standard Library
PositionId
Gets the ID of position, in which the deal was involved.
long PositionId() const
Return Value
ID of position, in which the deal was involved.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3318
Standard Library
Volume
Gets the volume of deal.
double Volume() const
Return Value
Volume of deal.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3319
Standard Library
Price
Gets the deal price.
double Price() const
Return Value
Deal price.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3320
Standard Library
Commission
Gets the amount of commission of the deal.
double Commission() const
Return Value
Amount of commission of the deal.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3321
Standard Library
Swap
Gets the amount of swap when position is closed.
double Swap() const
Return Value
Amount of swap when position is closed.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3322
Standard Library
Profit
Gets the financial result of the deal.
double Profit() const
Return Value
Financial result of the deal (in deposit currency).
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3323
Standard Library
Symbol
Gets the name of the deal symbol.
string Symbol() const
Return Value
Name of the deal symbol.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3324
Standard Library
Comment
Gets the deal comment.
string Comment() const
Return Value
Deal comment.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3325
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger(
ENUM_DEAL_PROPERTY_INTEGER prop_id,
// property ID
long&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3326
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble(
ENUM_DEAL_PROPERTY_DOUBLE prop_id,
// property ID
double&
// reference to variable
var
) const
Parameters
prop_id
[in] ID of double type property (value of ENUM_DEAL_PROPERTY_DOUBLE enumeration).
var
[out] Reference to double type variable to place result.
Return Value
true in case of success, false if unable to get property value.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3327
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString(
ENUM_DEAL_PROPERTY_STRING prop_id,
// property ID
string&
// reference to variable
var
) 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.
Return Value
true in case of success, false if unable to get property value.
Note
The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
3328
Standard Library
Return Value
Deal ticket.
// ticket
Parameters
ticket
[in] Deal ticket.
3329
Standard Library
SelectByIndex
Selects the deal by index for further access to its properties.
bool SelectByIndex(
int
index
// order index
Return Value
true in case of success, false if unable to select the deal.
3330
Standard Library
CTrade
CTrade is a class for easy access to the trade functions.
Description
CTrade class provides easy access to the trade functions.
Declaration
class CTrade : public CObject
Title
#include <Trade\Trade.mqh>
SetExpertMagicNumber
SetDeviationInPoints
SetTypeFilling
SetAsyncMode
Places a pending
parameters
order
with
OrderModify
OrderDelete
specified
PositionModify
PositionClose
PositionCloseBy
Additional methods
Buy
Sell
Opens a short
parameters
position
with
specified
3331
Standard Library
BuyLimit
BuyStop
SellLimit
SellStop
RequestAction
RequestActionDescription
RequestMagic
RequestOrder
RequestSymbol
RequestVolume
RequestPrice
RequestStopLimit
RequestSL
RequestTP
RequestDeviation
RequestType
RequestTypeDescription
RequestTypeFilling
RequestTypeFillingDescription
RequestTypeTime
RequestTypeTimeDescription
3332
Standard Library
RequestComment
RequestPosition
RequestPositionBy
CheckResultRetcode
CheckResultRetcodeDescription
CheckResultBalance
CheckResultEquity
CheckResultProfit
CheckResultMargin
CheckResultMarginFree
CheckResultMarginLevel
CheckResultComment
3333
Standard Library
ResultRetcode
ResultRetcodeDescription
ResultDeal
ResultOrder
ResultVolume
ResultPrice
ResultBid
ResultAsk
ResultComment
Auxiliary methods
PrintRequest
PrintResult
FormatRequest
FormatRequestResult
3334
Standard Library
LogLevel
Sets logging level for messages.
void LogLevel(
ENUM_LOG_LEVELS log_level
// logging level
Parameters
log_level
[in] Logging level.
Return Value
None.
Note
LOG_LEVEL_NO and less disables displaying any messages (set up automatically in the optimization
mode). LOG_LEVEL_ERRORS enables displaying only error messages (value by default).
LOG_LEVEL_ALL and greater enables displaying any messages (set up automatically in the test
mode).
ENUM_LOG_LEVELS
Identifier
Description
Value
LOG_LEVEL_NO
LOG_LEVEL_ERRORS
Only error
displayed
LOG_LEVEL_ALL
messages
are
3335
Standard Library
SetExpertMagicNumber
Sets the expert ID.
void SetExpertMagicNumber(
ulong magic
// ID
Parameters
magic
[in] New ID of the expert.
Return Value
None.
3336
Standard Library
SetDeviationInPoints
Sets the allowed deviation.
void SetDeviationInPoints(
ulong deviation
// deviation
Parameters
deviation
[in] Allowed deviation.
Return Value
None.
3337
Standard Library
SetTypeFilling
Sets filling type of the order.
void SetTypeFilling(
ENUM_ORDER_TYPE_FILLING filling
Parameters
filling
[in] Order filling type (value of ENUM_ORDER_TYPE_FILLING enumeration).
Return Value
None.
3338
Standard Library
SetAsyncMode
Sets asynchronous mode for trade operations.
void SetAsyncMode(
bool mode
Parameters
mode
[in] Asynchronous mode flag.
Return Value
None.
Note
This mode is used for asynchronous (without waiting for the trade server's response to a sent
request) trade operations (see OrderSendAsync).
3339
Standard Library
SetMarginMode
Sets margin calculation mode in accordance with the current account settings.
void SetMarginMode()
Return Value
No.
Note
The margin calculation mode is specified in ENUM_ACCOUNT_MARGIN_MODE.
3340
Standard Library
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,
double
tp,
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.
Return Value
true - in case of successful check of the basic structures, otherwise - false.
3341
Standard Library
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().
3342
Standard Library
OrderModify
Modifies the pending order parameters.
bool OrderModify(
ulong
ticket,
// order ticket
double
price,
// execution price
double
sl,
double
tp,
ENUM_ORDER_TYPE_TIME type_time,
// type by expiration
datetime
expiration,
// expiration
double
stoplimit
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).
stoplimit
[in] New price used for setting a Limit order when the price reaches price value. It is specified
only for StopLimit orders.
Return Value
true - in case of successful check of the basic structures, otherwise - false.
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().
3343
Standard Library
OrderDelete
Deletes the pending order.
bool OrderDelete(
ulong ticket
// order ticket
Parameters
ticket
[in] Order ticket.
Return Value
true - in case of successful check of the basic structures, otherwise - false.
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().
3344
Standard Library
PositionOpen
Opens a position with the specified parameters.
bool PositionOpen(
const string
symbol,
// symbol
ENUM_ORDER_TYPE order_type,
double
volume,
// position volume
double
price,
// execution price
double
sl,
double
tp,
const string
comment=""
// comment
Parameters
symbol
[in] Name of trade instrument, by which it is intended to open position.
order_type
[in] Order type (trade operation) to open position (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.
Return Value
true - in case of successful check of the basic structures, otherwise - false.
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().
3345
Standard Library
PositionModify
Modifies the position parameters by specified symbol.
bool PositionModify(
const string symbol,
// symbol
double
sl,
double
tp
// position ticket
double
sl,
double
tp
Parameters
symbol
[in] Name of trade instrument, by which it is intended to modify position.
ticket
[in] Ticket of the position to be modified.
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).
Return Value
true - in case of successful check of the basic structures, otherwise - false.
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().
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol. In this case, PositionModify will modify the position with the lowest
ticket.
3346
Standard Library
PositionClose
Closes a position by the specified symbol.
bool PositionClose(
const string symbol,
// symbol
ulong
// deviation
deviation=ULONG_MAX
// Position ticket
ulong
// Deviation
deviation=ULONG_MAX
Parameters
symbol
[in] Name of trade instrument, by which it is intended to close position.
ticket
[in] Ticket of a closed position.
deviation=ULONG_MAX
[in] Maximal deviation from the current price (in points).
Return Value
true - in case of successful check of the basic structures, otherwise - false.
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().
For the "netting" interpretation of positions (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and
ACCOUNT_MARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol. In this case, PositionClose will close a position with the lowest ticket.
3347
Standard Library
PositionCloseBy
Closes a position with the specified ticket by an opposite position.
bool PositionCloseBy(
const ulong ticket,
// Position ticket
const ulong
ticket_by
Parameters
ticket
[in] Ticket of the closed position.
ticket_by
[in] Ticket of the opposite position used for closing.
Returned value
true if the basic check of structures is successful, otherwise false.
Note
A successful completion of the PositionCloseBy(...) method does not always mean a successful
execution of a trading operation. You should call the ResultRetcode() method to check the result of a
trade request (trade server return code).
3348
Standard Library
Buy
Opens a long position with specified parameters.
bool Buy(
double
volume,
// position volume
// symbol
double
price=0.0,
// price
double
sl=0.0,
double
tp=0.0,
// 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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3349
Standard Library
Sell
Opens a short position with specified parameters.
bool Sell(
double
volume,
// position volume
// symbol
double
price=0.0,
// price
double
sl=0.0,
double
tp=0.0,
// 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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3350
Standard Library
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,
double
tp=0.0,
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC,
// order lifetime
datetime
expiration=0,
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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3351
Standard Library
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,
double
tp=0.0,
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC,
// order lifetime
datetime
expiration=0,
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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3352
Standard Library
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,
double
tp=0.0,
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC,
// order lifetime
datetime
expiration=0,
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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3353
Standard Library
SellStop
Places the pending order of Sell 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,
double
tp=0.0,
ENUM_ORDER_TYPE_TIME type_time=ORDER_TIME_GTC,
// order lifetime
datetime
expiration=0,
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.
Return Value
true - in case of successful check of the structures, otherwise - false.
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().
3354
Standard Library
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.
Return Value
None.
3355
Standard Library
RequestAction
Gets the trade operation type.
ENUM_TRADE_REQUEST_ACTIONS RequestAction() const
Return Value
Trade operation type used in the last request.
3356
Standard Library
RequestActionDescription
Gets the trade operation type as string.
string RequestActionDescription() const
Return Value
Trade operation type (as string) used in the last request.
3357
Standard Library
RequestMagic
Gets the magic number of the Expert Advisor.
ulong RequestMagic() const
Return Value
The magic number (ID) of the Expert Advisor, used in the last request.
3358
Standard Library
RequestOrder
Gets the order ticket used in the last request.
ulong RequestOrder() const
Return Value
Order ticket of the last request.
3359
Standard Library
RequestSymbol
Gets the name of the symbol used in the last request.
string RequestSymbol() const
Return Value
The name of the symbol used in the last request.
3360
Standard Library
RequestVolume
Gets the trade volume (in lots) used in the last request.
double RequestVolume() const
Return Value
The trade volume (in lots) used in the last request.
3361
Standard Library
RequestPrice
Gets the price used in the last request.
double RequestPrice() const
Return Value
Order price used in the last request.
3362
Standard Library
RequestStopLimit
Gets the price of pending order of Stop Limit type used in the last request.
double RequestStoplimit() const
Return Value
The price of pending order of Stop Limit type used in the last request.
3363
Standard Library
RequestSL
Gets the Stop Loss price of the order used in the last request.
double RequestSL() const
Return Value
The Stop Loss price used in the last request.
3364
Standard Library
RequestTP
Gets the Take Profit price of the order used in the last request.
double RequestTP() const
Return Value
The Take Profit price used in the last request.
3365
Standard Library
RequestDeviation
Gets the price deviation of the order used in the last request.
ulong RequestDeviation() const
Return Value
The price deviation of the order used in the last request.
3366
Standard Library
RequestType
Gets the type of the order used in the last request.
ENUM_ORDER_TYPE RequestType() const
Return Value
Order type used in the last request (value of ENUM_ORDER_TYPE enumeration).
3367
Standard Library
RequestTypeDescription
Gets the type of the order (as string) used in the last request.
string RequestTypeDescription() const
Return Value
The order type (as string) used in the last request.
3368
Standard Library
RequestTypeFilling
Gets the filling type of the order used in the last request.
ENUM_ORDER_TYPE_FILLING RequestTypeFilling() const
Return Value
The filling type of the order (value of ENUM_ORDER_TYPE_FILLING) used in the last request.
3369
Standard Library
RequestTypeFillingDescription
Gets the filling type of the order (as string) used in the last request.
string RequestTypeFillingDescription() const
Return Value
The filling type (as string) of the order used in the last request.
3370
Standard Library
RequestTypeTime
Gets the validity period of the order used in the last request.
ENUM_ORDER_TYPE_TIME RequestTypeTime() const
Return Value
The validity period of the order (value of ENUM_ORDER_TYPE_TIME enumeration) used in the last
request.
3371
Standard Library
RequestTypeTimeDescription
Gets the validity period of the order (as string) used in the last request.
string RequestTypeTimeDescription() const
Return Value
The validity period of the order (as string) used in the last request.
3372
Standard Library
RequestExpiration
Gets the expiration time of the order used in the last request.
datetime RequestExpiration() const
Return Value
The expiration time of the order used in the last request.
3373
Standard Library
RequestComment
Gets the comment of the order used in the last request.
string RequestComment() const
Return Value
The comment of the order used in the last request.
3374
Standard Library
RequestPosition
Gets position ticket.
ulong RequestPosition() const
Return value
Position ticket used in the last request.
3375
Standard Library
RequestPositionBy
Gets opposite position ticket.
ulong RequestPositionBy() const
Return value
Opposite position ticket used in the last request.
3376
Standard Library
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.
Return Value
None.
3377
Standard Library
ResultRetcode
Gets the code of request result.
uint ResultRetcode() const
Return Value
The Code of request result.
3378
Standard Library
ResultRetcodeDescription
Gets the code of request result as text.
string ResultRetcodeDescription() const
Return Value
Code of the last request result as text.
3379
Standard Library
ResultDeal
Gets the deal ticket.
ulong ResultDeal() const
Return Value
Deal ticket, if the deal is executed.
3380
Standard Library
ResultOrder
Gets the order ticket.
ulong ResultOrder() const
Return Value
Order ticket, if the order is placed.
3381
Standard Library
ResultVolume
Gets the volume of deal or order.
double ResultVolume() const
Return Value
Volume of deal or order.
3382
Standard Library
ResultPrice
Gets the price, confirmed by broker.
double ResultPrice() const
Return Value
Price, confirmed by the broker.
3383
Standard Library
ResultBid
Gets the current bid price (the requote).
double ResultBid() const
Return Value
Current bid price (the requote).
3384
Standard Library
ResultAsk
Gets the current ask price (the requote).
double ResultAsk() const
Return Value
Current ask price (the requote).
3385
Standard Library
ResultComment
Gets the broker comment.
string ResultComment() const
Return Value
Broker comment to the operation.
3386
Standard Library
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.
Return Value
None.
3387
Standard Library
CheckResultRetcode
Gets the value of the retcode field of MqlTradeCheckResult type, filled while checking of the request
correctness.
uint CheckResultRetcode() const
Return Value
The value of the retcode field (error code) of MqlTradeCheckResult type, filled while checking of the
request correctness.
3388
Standard Library
CheckResultRetcodeDescription
Gets the string description of the retcode field of MqlTradeCheckResult type, filled while checking of
the request correctness.
string ResultRetcodeDescription() const
Return Value
The string description of the retcode field (Error code) of MqlTradeCheckResult type, filled while
checking of the request correctness.
3389
Standard Library
CheckResultBalance
Gets the value of the balance field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultBalance() const
Return 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.
3390
Standard Library
CheckResultEquity
Gets the value of the equity field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultEquity() const
Return 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.
3391
Standard Library
CheckResultProfit
Gets the value of the profit field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultProfit() const
Return 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.
3392
Standard Library
CheckResultMargin
Gets the value of the margin field of MqlTradeCheckResult type, filled while checking of the request
correctness.
double CheckResultMargin() const
Return Value
The value of the margin field (margin required for the trade operation) of MqlTradeCheckResult
type, filled while checking of the request correctness.
3393
Standard Library
CheckResultMarginFree
Gets the value of the margin_free field of MqlTradeCheckResult type, filled while checking of the
request correctness.
double CheckResultMarginFree() const
Return 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.
3394
Standard Library
CheckResultMarginLevel
Gets the value of the margin_level field of MqlTradeCheckResult type, filled while checking of the
request correctness.
double CheckResultMarginLevel() const
Return 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.
3395
Standard Library
CheckResultComment
The value of the comment field of MqlTradeCheckResult type, filled while checking of the request
correctness.
string CheckResultComment() const
Return Value
The value of the comment field (Comment to the reply code, error description) of
MqlTradeCheckResult type, filled while checking of the request correctness.
3396
Standard Library
PrintRequest
Prints the last request parameters into journal.
void PrintRequest() const
Return Value
None.
3397
Standard Library
PrintResult
Prints the results of the last request into journal.
void PrintResult() const
Return Value
None.
3398
Standard Library
FormatRequest
Prepares the formatted string with last request parameters.
string FormatRequest(
string&
str,
// target string
// request
) const
Parameters
str
[in] Target string, passed by reference.
request
[in] A structure of MqlTradeRequest type with parameters of the last request.
Return Value
None.
3399
Standard Library
FormatRequestResult
Prepares the formatted string with results of the last request execution.
string FormatRequestResult(
string&
str,
// string
// request structure
const MqlTradeResult&
// result structure
result
) 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.
Return Value
None.
3400
Standard Library
CTerminalInfo
CTerminalInfo is a class for simplified access to the properties of mql5 program environment.
Description
CTerminalInfo class provides access to the properties of mql5 program environment.
Declaration
class CTerminalInfo : public CObject
Title
#include <Trade\TerminalInfo.mqh>
IsConnected
IsDLLsAllowed
IsTradeAllowed
IsEmailEnabled
IsFtpEnabled
MaxBars
CodePage
CPUCores
MemoryPhysical
MemoryTotal
MemoryAvailable
about
the
physical
3401
Standard Library
MemoryUsed
IsX64
OpenCLSupport
DiskSpace
Name
Company
Path
DataPath
CommonDataPath
InfoString
3402
Standard Library
Build
Gets the build number of the client terminal.
int CBuild() const
Return Value
Build number of the client terminal.
Note
To get the build number it uses the TerminalInfoInteger() function (TERMINAL_BUILD property).
3403
Standard Library
IsConnected
Gets the information about connection to trade server.
bool IsConnected() const
Return Value
true, if terminal is connected to trade server, otherwise false.
Note
To get connection status it uses the TerminalInfoInteger() function (TERMINAL_CONNECTED property).
3404
Standard Library
IsDLLsAllowed
Gets the information about permission of DLL usage.
bool IsDLLsAllowed() const
Return Value
true, if DLL usage is allowed, otherwise false.
Note
To get information on permission of DLL usage it uses the TerminalInfoInteger() function
(TERMINAL_DLLS_ALLOWED property).
3405
Standard Library
IsTradeAllowed
Gets the information about permission to trade.
bool IsTradeAllowed() const
Return Value
true, if trade allowed, otherwise false.
Note
To get information on permission to trade it uses
(TERMINAL_TRADE_ALLOWED property).
3406
Standard Library
IsEmailEnabled
Gets the information about permission to send e-mails to SMTP-server and login, specified in the
terminal settings.
bool IsEmailEnabled() const
Return Value
true, if sending of e-mails is allowed, otherwise false.
Note
To get information on the permission of e-mails sending it uses the TerminalInfoInteger() function
(TERMINAL_EMAIL_ENABLED property).
3407
Standard Library
IsFtpEnabled
Gets the information about permission to send trade reports to FTP server and login, specified in the
terminal settings.
bool IsFtpEnabled() const
Return Value
true, if trade reports sending to FTP server is allowed, otherwise false.
Note
To get information about permission to send trade reports it uses the TerminalInfoInteger() function
(TERMINAL_FTP_ENABLED property).
3408
Standard Library
MaxBars
Gets the maximum number of bars on chart, specified in the client terminal settings.
int MaxBars() const
Return Value
Maximum number of bars on the chart.
Note
To get the maximum number of bars on the chart it uses the TerminalInfoInteger() function
(TERMINAL_MAXBARS property).
3409
Standard Library
CodePage
Gets the information about code page of the language in the client terminal.
int CodePage() const
Return Value
Code page of the language in the client terminal.
Note
To get the code page it uses the TerminalInfoInteger() function (TERMINAL_CODEPAGE property).
3410
Standard Library
CPUCores
Gets the information about the amount of CPU cores in the system.
int CPUCores() const
Return Value
Amount of CPU cores in the system.
Note
To get the amount of CPU cores it uses the TerminalInfoInteger() function (TERMINAL_CPU_CORES
property).
3411
Standard Library
MemoryPhysical
Gets the information about the physical memory (in Mb).
int MemoryPhysical() const
Return Value
Physical memory (in Mb).
Note
To
get
the
physical
memory
(TERMINAL_MEMORY_PHYSICAL property).
it
uses
the
TerminalInfoInteger()
function
3412
Standard Library
MemoryTotal
Gets the information about the total memory, available for the client terminal/agent (in Mb).
int MemoryTotal() const
Return Value
Total memory (in Mb), available for the terminal/agent.
Note
To get the total memory it uses the TerminalInfoInteger() function (TERMINAL_MEMORY_TOTAL
property).
3413
Standard Library
MemoryAvailable
Gets the information about the free memory, available for the client terminal/agent (in Mb).
int MemoryTotal() const
Return Value
Free memory (in Mb), available for the terminal/agent.
Note
To get the free memory it uses the TerminalInfoInteger() function (TERMINAL_MEMORY_TOTAL
property).
3414
Standard Library
MemoryUsed
Gets the information about the memory, used by the client terminal/agent (in Mb).
int MemoryUsed() const
Return Value
The memory, used by the client terminal/agent (in Mb).
Note
To get the memory, used by the terminal it uses
(TERMINAL_MEMORY_USED property).
3415
Standard Library
IsX64
Gets the information about the type of the client terminal.
bool IsX64() const
Return Value
true, if 64-bit version is used, otherwise false.
Note
To get the type of the client terminal it uses the TerminalInfoInteger() function (TERMINAL_X64
property).
3416
Standard Library
OpenCLSupport
Gets the information about the version of OpenCL, supported by video card.
int OpenCLSupport() const
Return Value
The returned value has the following form: 0x00010002 = "1.2". The 0 means that OpenCL is not
supported.
Note
To
get
the
version
of
OpenCL
(TERMINAL_OPENCL_SUPPORT property).
it
uses
the
TerminalInfoInteger()
function
3417
Standard Library
DiskSpace
Gets the information about free disk space, available for the client terminal/agent (in Mb).
int MDiskSpace() const
Return Value
Free disk space (in Mb), available for the client terminal/agent (for files, saved to MQL5\Files
folder).
Note
To get the free disk space it uses the TerminalInfoInteger() function (TERMINAL_DISK_SPACE
property).
3418
Standard Library
Language
Gets the information about the language in the client terminal.
string Language() const
Return Value
Language, used in the client terminal.
Note
To get the language it uses the TerminalInfoString() function (TERMINAL_LANGUAGE property).
3419
Standard Library
Name
Gets the information of the name of the client terminal.
string Name() const
Return Value
Name of the client terminal.
Note
To get the name of the client terminal it uses the TerminalInfoString() function (TERMINAL_NAME
property).
3420
Standard Library
Company
Gets the information about the name of the broker.
string Company() const
Return Value
The name of the broker.
Note
To get the broker name it uses the TerminalInfoString() function (TERMINAL_COMPANY property).
3421
Standard Library
Path
Gets the client terminal folder.
string Path() const
Return Value
The client terminal folder.
Note
To get the client terminal folder it uses the TerminalInfoString() (TERMINAL_PATH property).
3422
Standard Library
DataPath
Gets the information about the terminal data folder.
string DataPath() const
Return Value
Data folder of the client terminal.
Note
To get the client terminal data
(TERMINAL_DATA_PATH property).
folder
it
uses
the
TerminalInfoString()
function
3423
Standard Library
CommonDataPath
Gets the common data folder of all client terminals, installed on the computer.
string CommonDataPath() const
Return Value
Common data folder.
Note
To get common data folder it uses the TerminalInfoString() function (COMMON_DATA_PATH
property).
3424
Standard Library
InfoInteger
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.
ENUM_TERMINAL_INFO_INTEGER.
Can
be
one
of
the
values
Return Value
Value of int type.
Note
To get the property value it uses the TerminalInfoInteger() function.
of
the
enumeration
3425
Standard Library
InfoString
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.
ENUM_TERMINAL_INFO_STRING.
Perhaps
one
of
the
Return Value
Value of string type.
Note
To get the property value it uses the TerminalInfoString() function.
values
of
the
enumeration
3426
Standard Library
Description
CExpertBase
CExpert
CExpertSignal
CExpertTrailing
CExpertMoney
Description
CSignalAC
CSignalAMA
CSignalAO
CSignalBearsPower
CSignalBullsPower
CSignalCCI
CSignalDeM
CSignalDEMA
CSignalEnvelopes
CSignalFrAMA
CSignalITF
3427
Standard Library
Description
CSignalMACD
CSignalMA
CSignalSAR
CSignalRSI
CSignalRVI
CSignalStoch
CSignalTRIX
CSignalTEMA
CSignalWPR
Description
CTrailingFixedPips
CTrailingMA
CTrailingNone
CTrailingPSAR
Description
CMoneyFixedLot
CMoneyFixedMargin
CMoneyFixedRisk
3428
Standard Library
CMoneyNone
CMoneySizeOptimized
3429
Standard Library
Description
CExpertBase
CExpert
CExpertSignal
CExpertTrailing
CExpertMoney
3430
Standard Library
CExpertBase
CExpertBase is a base class for the CExpert class and all trading strategy classes.
Description
CExpertBase provides the data and methods, which are common to all objects of the Expert Advisor.
Declaration
class CExpertBase : public CObject
Title
#include <Expert\ExpertBase.mqh>
Class Methods
Public Methods:
Initialization
virtual Init
virtual ValidationSettings
Parameters
Symbol
Period
Magic
virtual SetOtherSeries
virtual InitIndicators
TrendType
UsedSeries
EveryTick
Access to Timeseries
Open
3431
Standard Library
High
Low
Close
Spread
Time
TickVolume
RealVolume
Protected Methods:
Initialization of Timeseries
InitOpen
InitHigh
InitLow
InitClose
InitSpread
InitTime
InitTickVolume
InitRealVolume
Service Methods
virtual PriceLevelUnit
virtual StartIndex
virtual CompareMagic
3432
Standard Library
InitPhase
Gets the current phase of the object initialization.
ENUM_INIT_PHASE InitPhase()
Return Value
Current phase of the object initialization.
Note
The object initialization consist of several phases:
1. Start initialization.
- start
- finish
- allowed
- not allowed
2. Parameters setting phase. In this phase you need to set all the object parameters, used for
creation of indicators.
- start
- after successful completion of the Init(...) method
- finish
- after successful completion of the ValidationSettings() method
- allowed
- call of Symbol(...) and Period(...) methods
- not allowed - call of the Init(...), SetPriceSeries(...), SetOtherSeries(...) and InitIndicators(...)
methods
3. Checking of parameters.
- start
- after successful completion of the ValidationSettings() method
- finish
- after successful completion of the InitIndicators(...) method
- allowed
- call of the Symbol(...), Period(...) and InitIndicators(...) methods
- not allowed - call of any other initialization methods
4. Finish of initialization.
- start
- not allowed
3433
Standard Library
TrendType
Sets trend type.
void TrendType(
M_TYPE_TREND
value
// new value
Parameters
value
[in] New value of trend type.
Return Value
None.
3434
Standard Library
UsedSeries
Gets the bitmask of timeseries used.
int UsedSeries()
Return Value
The list of used timeseries as bitmask.
Note
If the bit is set, the corresponding timeseries is used, if it isn't set, the timeseries is not used.
The bit-timeseries correspondence:
bit 0 - Open timeseries,
bit 1 - High timeseries,
bit 2 - Low timeseries,
bit 3 - Close timeseries,
bit 4 - Spread timeseries,
bit 5 - Time timeseries,
bit 6 - TickVolume timeseries,
bit 7 - RealVolume timeseries.
3435
Standard Library
EveryTick
Sets the "Every tick" flag.
void EveryTick(
bool
value
// flag
Parameters
value
[in] New value of a flag.
Return Value
None.
Note
If the flag is not set, the processing method is called only at new bar on the working timeframe and
symbol.
3436
Standard Library
Open
Gets the element of the Open timeseries by index.
double Open(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the Open timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3437
Standard Library
High
Gets the element of the High timeseries by index.
double High(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the High timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3438
Standard Library
Low
Gets the element of the Low timeseries by index.
double Low(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the Low timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3439
Standard Library
Close
Gets the element of the Close timeseries by index.
double Close(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the Close timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3440
Standard Library
Spread
Gets the element of the Spread timeseries by index.
double Spread(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the Spread timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3441
Standard Library
Time
Gets the element of the Time timeseries by index.
datetime Time(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the Time timeseries element with specified index,
otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3442
Standard Library
TickVolume
Gets the element of the TickVolume timeseries by index.
long TickVolume(
int
ind
// Index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the TickVolume timeseries element with specified
index, otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3443
Standard Library
RealVolume
Gets the element of the RealVolume timeseries by index.
long RealVolume(
int
ind
// index
Parameters
ind
[in] Element index.
Return Value
If successful, it returns the numerical value of the RealVolume timeseries element with specified
index, otherwise it returns EMPTY_VALUE.
Note
The EMPTY_VALUE is returned in two cases:
1. Timeseries is not used (the corresponding bit is not set).
2. Element index is out of range.
3444
Standard Library
Init
Initializes the object.
bool Init(
CSymbolInfo
symbol,
// symbol
ENUM_TIMEFRAMES period,
// timeframe
double
// point
point
Parameters
symbol
[in] Pointer to the object of CSymbolInfo type for access to symbol information.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
point
[in] The "weight" of 2/4-digit point.
Return Value
true if successful, otherwise false.
3445
Standard Library
Symbol
Sets the symbol.
bool Symbol(
string
name
// symbol
Parameters
name
[in] Symbol.
Return Value
true if successful, otherwise false.
Note
The setting of working symbol is necessary if the object uses the symbol, different from symbol,
defined at the initialization.
3446
Standard Library
Period
Sets the timeframe.
bool Period(
ENUM_TIMEFRAMES value
// timeframe
Parameters
value
[in] Timeframe.
Return Value
true if successful, otherwise false.
Note
The setting of working timeframe is necessary if the object uses the timeframe, different from
timeframe, defined at the initialization.
3447
Standard Library
Magic
Sets the Expert Advisor ID.
void Magic(
ulong value
// magic
Parameters
value
[in] Expert Advisor ID.
Return Value
None.
3448
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
3449
Standard Library
SetPriceSeries
Sets pointers to external price series.
virtual bool SetPriceSeries(
CiOpen*
open,
// pointer
CiHigh*
high,
// pointer
CiLow*
low,
// pointer
CiClose*
close
// pointer
Parameters
open
[in] Pointer to Open timeseries.
high
[in] Pointer to High timeseries.
low
[in] Pointer to Low timeseries.
close
[in] Pointer to Close timeseries.
Return Value
true if successful, otherwise false.
Note
The setting of pointers to external timeseries (price series) is necessary if the object uses
timeseries of the symbol and timeframe, different from the symbol and timeframe, defined at
initialization.
3450
Standard Library
SetOtherSeries
Sets pointers to external non-price series.
virtual bool SetOtherSeries(
CiSpread*
spread,
// pointer
CiTime*
time,
// pointer
CiTickVolume*
tick_volume,
// pointer
CiRealVolume*
real_volume
// pointer
Parameters
spread
[in] Pointer to Spread timeseries.
time
[in] Pointer to Time timeseries.
tick_volume
[in] Pointer to TickVolume timeseries.
real_volume
[in] Pointer to RealVolume timeseries.
Return Value
true if successful, otherwise false.
Note
The setting of pointers to external timeseries (non-price series) is necessary if the object uses
timeseries of the symbol and timeframe, different from the symbol and timeframe, defined at
initialization.
3451
Standard Library
InitIndicators
Initializes all indicators and time series.
virtual bool InitIndicators(
CIndicators* indicators=NULL
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The timeseries are initialized only if the object uses the symbol or timeframe, different from the
symbol or timeframe, defined at initialization.
3452
Standard Library
InitOpen
Initalizes the Open timeseries.
bool InitOpen(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The Open timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different from
the symbol/timeframe defined at initialization (and timeseries is used further).
3453
Standard Library
InitHigh
Initalizes the High timeseries.
bool InitHigh(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The High timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different from
the symbol/timeframe defined at initialization (and timeseries is used further).
3454
Standard Library
InitLow
Initalizes the Low timeseries.
bool InitLow(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The Low timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different from
the symbol/timeframe defined at initialization (and timeseries is used further).
3455
Standard Library
InitClose
Initalizes the Close timeseries.
bool InitClose(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The Close timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different from
the symbol/timeframe defined at initialization (and timeseries is used further).
3456
Standard Library
InitSpread
Initalizes the Spread timeseries.
bool InitSpread(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The Spread timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different
from the symbol/timeframe defined at initialization (and timeseries is used further).
3457
Standard Library
InitTime
Initalizes the Time timeseries.
bool InitTime(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The Time timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different from
the symbol/timeframe defined at initialization (and timeseries is used further).
3458
Standard Library
InitTickVolume
Initalizes the TickVolume timeseries.
bool InitTickVolume(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The TickVolume timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different
from the symbol/timeframe defined at initialization (and timeseries is used further).
3459
Standard Library
InitRealVolume
Initalizes the RealVolume timeseries.
bool InitRealVolume(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The RealVolume timeseries is initialized only if Expert Advisor uses the symbol/timeframe, different
from the symbol/timeframe defined at initialization (and timeseries is used further).
3460
Standard Library
PriceLevelUnit
Gets the price level unit.
virtual double PriceLevelUnit()
Return Value
The value of Price Level unit.
Note
The method of a base class returns the "weight" of the 2/4 digits point.
3461
Standard Library
StartIndex
Gets the index of starting bar to analyze.
virtual int StartIndex()
Return Value
The index of starting bar to analyze.
Note
The method returns 0 if the flag to analyze current bar is set to true (analysis from the current bar).
If the flag is not set, it returns 1 (analysis from the last completed bar).
3462
Standard Library
CompareMagic
Compares the Expert Advisor ID (magic) with the specified value.
virtual bool CompareMagic(
ulong magic
// value to compare
Parameters
magic
[in] Value to compare.
Return Value
true if they are equal, otherwise false.
3463
Standard Library
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.
How to use it:
1. Prepare an algorithm of the strategy;
2. Create your own class, inherited from CExpert class;
3. Override the virtual methods in your class with your own algorithms.
Description
The CExpert class is a set of virtual methods for implementation of trading strategies.
Note
A position is recognized as belonging to an Expert Advisor and managed by it based on the pair of
properties m_symbol and m_magic. In the "hedging" mode, multiple positions can be open for the
same symbol, therefore the m_magic value is important.
Declaration
class CExpert : public CExpertBase
Title
#include <Expert\Expert.mqh>
Class Methods
Initialization
Init
virtual InitSignal
virtual InitTrailing
virtual InitMoney
virtual InitTrade
virtual ValidationSettings
virtual InitIndicators
virtual InitParameters
virtual Deinit
virtual DeinitSignal
virtual DeinitTrailing
virtual DeinitMoney
3464
Standard Library
virtual DeinitTrade
virtual DeinitIndicators
Parameters
Magic
MaxOrders
OnTickProcess
OnTradeProcess
OnTimerProcess
OnChartEventProcess
OnBookEventProcess
OnTrade
OnTimer
OnChartEvent
OnBookEvent
Update Methods
Refresh
Processing
Processing
CheckOpenLong
CheckOpenShort
OpenLong
OpenShort
CheckCloseLong
CheckCloseShort
CloseAll
3465
Standard Library
Close
CloseLong
CloseShort
CheckReverseLong
CheckReverseShort
ReverseLong
ReverseShort
Checks
conditions
parameters
to
modify
CheckTrailingStopLong
CheckTrailingStopShort
Checks Trailing
position
TrailingStopLong
TrailingStopShort
CheckTrailingOrderLong
CheckTrailingOrderShort
TrailingOrderLong
TrailingOrderShort
Stop conditions
position
of
short
CheckDeleteOrderShort
DeleteOrders
DeleteOrder
DeleteOrderLong
DeleteOrderShort
LotOpenShort
3466
Standard Library
LotReverse
Gets trade
operation
volume
for
position
reverse
HistoryPoint
CheckTradeState
Event flags
WaitEvent
NoWaitEvent
TradeEventOrderTriggered
TradeEventPositionOpened
TradeEventPositionVolumeChanged
TradeEventPositionModified
TradeEventPositionClosed
TradeEventOrderPlaced
TradeEventOrderModified
TradeEventOrderDeleted
TradeEventNotIdentified
Service methods
TimeframeAdd
TimeframesFlags
SelectPosition
3467
Standard Library
Init
Class instance initialization method.
bool Init(
string
symbol,
// symbol
ENUM_TIMEFRAMES
period,
// timeframe
bool
every_tick,
// flag
ulong
magic
// magic
Parameters
symbol
[in] Symbol.
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
every_tick
[in] Flag.
magic
[in] Expert Advisor ID (Magic number).
Return Value
true if successful, otherwise false.
Note
If every_tick is set to true, the Processing() method is called at each tick of the working symbol.
otherwise, the Processing() is called only when at new bar of the working symbol.
3468
Standard Library
Magic
Sets the Expert Advisor ID (magic).
void Magic(
ulong value
// new value
Parameters
value
[in] New value of Expert Advisor ID.
Return Value
None.
Note
It sets the value of Expert Advisor ID (magic) to the following classes: Trade, Signal, Money,
Trailing.
Implementation
//+------------------------------------------------------------------+
//| Sets magic number for object and its dependent objects
|
//| INPUT: value - new value of magic number.
|
//| OUTPUT: no.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
void CExpert::Magic(ulong value)
{
if(m_trade!=NULL)
m_trade.SetExpertMagicNumber(value);
if(m_signal!=NULL)
m_signal.Magic(value);
if(m_money!=NULL)
m_money.Magic(value);
if(m_trailing!=NULL) m_trailing.Magic(value);
//--CExpertBase::Magic(value);
}
3469
Standard Library
InitSignal
Initializes Trading Signal object.
virtual bool InitSignal(
CExpertSignal*
signal=NULL,
// pointer
Parameters
signal
[in] Pointer to CExpertSignal class object (or its heis).
Return Value
true if successful, otherwise false.
Note
If signal is NULL, the CExpertSignal class will be used, it does nothing.
3470
Standard Library
InitTrailing
Initializes Trailing Stop object.
virtual bool InitTrailing(
CExpertTrailing*
trailing=NULL,
// pointer
Parameters
trailing
[in] Pointer to CExpertTrailing class object (or its heir).
Return Value
true if successful, otherwise false.
Note
If trailing is NULL, the ExpertTrailing class will be used, it does nothing.
3471
Standard Library
InitMoney
Initializes the Money Management object.
virtual bool InitMoney(
CExpertMoney*
money=NULL,
// pointer
Parameters
money
[in] Pointer to CExpertMoney class object (or its heir).
Return Value
true if successful, otherwise false.
Note
If money is NULL, the CExpertMoney class will be used, it uses the minimum lot.
3472
Standard Library
InitTrade
Initializes the Trade object.
virtual bool InitTrade(
ulong
magic,
// magic
CExpertTrade*
trade=NULL
// pointer
Parameters
magic
[in] Expert Advisor ID (will be used in trade requests).
trade
[in] Pointer to CExpertTrade object.
Return Value
true if successful, otherwise false.
3473
Standard Library
Deinit
Class instance deinitialization method.
virtual void Deinit()
Return Value
None.
3474
Standard Library
OnTickProcess
Sets a flag to proceed the OnTick event.
void OnTickOProcess(
bool
value
// flag
Parameters
value
[in] Flag to proceed the OnTick event.
Return Value
None.
Note
If the flag is true, the OnTick event is proceed, by default, the flag is set to true.
3475
Standard Library
OnTradeProcess
Sets a flag to proceed the OnTrade event.
void OnTradeProcess(
bool
value
// flag
Parameters
value
[in] Flag to proceed the OnTrade event.
Return Value
None.
Note
If the flag is true, the OnTrade event is proceed, by default, the flag is set to false.
3476
Standard Library
OnTimerProcess
Sets a flag to proceed the OnTimer event.
void OnTimerProcess(
bool
value
// flag
Parameters
value
[in] Flag to proceed the OnTimer event.
Return Value
None.
Note
If the flag is true, the OnTimer event is proceed, by default, the flag is set to false.
3477
Standard Library
OnChartEventProcess
Sets a flag to proceed the OnChartEvent event.
void OnChartEventProcess(
bool
value
// flag
Parameters
value
[in] Flag to proceed the OnChartEvent event.
Return Value
None.
Note
If the flag is true, the OnChartEvent event is proceed, by default, the flag is set to false.
3478
Standard Library
OnBookEventProcess
Sets a flag to proceed the OnBookEvent event.
void OnChartEventProcess(
bool
value
// flag
Parameters
value
[in] Flag to proceed the OnBookEvent event.
Return Value
None.
Note
If the flag is true, the OnBookEvent event is proceed, by default, the flag is set to false.
3479
Standard Library
Return Value
Maximum amount of allowed orders.
max_orders
// new value
Parameters
max_orders
[in] New value of maximum amount of allowed orders.
Return Value
None.
Note
By default, the maximum amount of allowed orders = 1.
3480
Standard Library
Signal
Gets the pointer to the Trade Signal object.
CExpertSignal* Signal() const
Return Value
Pointer to the Trade Signal object.
3481
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
It also checks the settings of all the Expert Advisor objects.
3482
Standard Library
InitIndicators
Initializes all indicators and timeseries.
virtual bool InitIndicators(
CIndicators* indicators=NULL
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The timeseries are initialized if the object uses a symbol or timeframe other than the ones defined
in the initialization. It calls consequentially InitIndicators() virtual methods of trading signal, trailing
stop and money management objects.
3483
Standard Library
OnTick
Event handler of the OnTick event.
virtual void OnTick()
Return Value
None.
3484
Standard Library
OnTrade
Event handler of the OnTrade event.
virtual void OnTrade()
Return Value
None.
3485
Standard Library
OnTimer
Event handler of the OnTimer event.
virtual void OnTimer()
Return Value
None.
3486
Standard Library
OnChartEvent
Event handler of the OnChartEvent event.
virtual void OnChartEvent(
const int
id,
// event id
const long&
lparam,
// long parameter
// double parameter
const string
// string parameter
sparam
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type.
dparam
[in] Event parameter of double type.
sparam
[in] Event parameter of string type.
Return Value
None.
3487
Standard Library
OnBookEvent
Event handler of the OnBookEvent event.
virtual void OnBookEvent(
const string&
symbol
// symbol
Parameters
symbol
[in] Symbol of OnBookEvent event.
Return Value
None.
3488
Standard Library
InitParameters
Initializes parameters of Expert Advisor.
virtual bool InitParameters()
Return Value
true if successful, otherwise false.
Note
The InitParameters() function of CExpert base class does nothing and always returns true.
3489
Standard Library
DeinitTrade
Deinitializes Trade object.
virtual void DeinitTrade()
Return Value
None.
3490
Standard Library
DeinitSignal
Deinitializes Signal object.
virtual void DeinitSignal()
Return Value
None.
3491
Standard Library
DeinitTrailing
Deinitializes Trailing object.
virtual void DeinitTrailing()
Return Value
None.
3492
Standard Library
DeinitMoney
Deinitializes Money Management object.
virtual void DeinitMoney()
Return Value
None.
3493
Standard Library
DeinitIndicators
Deinitializes all indicators and time series.
virtual void DeinitIndicators()
Return Value
None.
Note
It also deinitializes all indicators and time series of all auxiliary objects.
3494
Standard Library
Refresh
Updates all data.
virtual bool Refresh()
Return Value
true if further tick processing is needed, otherwise false.
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.
Implementation
//+------------------------------------------------------------------+
//| Refreshing data for processing
|
//| INPUT: no.
|
//| OUTPUT: true-if successful, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::Refresh()
{
MqlDateTime time;
//--- refresh rates
if(!m_symbol.RefreshRates()) return(false);
//--- check need processing
TimeToStruct(m_symbol.Time(),time);
if(m_period_flags!=WRONG_VALUE && m_period_flags!=0)
if((m_period_flags & TimeframesFlags(time))==0) return(false);
m_last_tick_time=time;
//--- refresh indicators
m_indicators.Refresh();
//--- ok
return(true);
}
3495
Standard Library
Processing
Main processing algorithm.
virtual bool Processing()
Return Value
true if trade operation has been executed, otherwise false.
Note
It does the following steps:
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 (CheckReverse() method). If position has been
"reversed", exit.
3. Checks conditions to close position (CheckClose() method). If position has been closed, skip step
4.
4. Checks conditions to modify position parameters (CheckTrailingStop() method). If position
parameters have been modified, exit.
5. Check the presence of pending orders on the symbol. If there isn't any pending order, go to step
9.
6. Checks condition to delete order (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 (CheckTrailingOrderLong() for buy orders
or CheckTrailingOrderShort() for sell orders). If the order parameters have been modified, exit.
8. Exit.
9. Checks conditions to open position (CheckOpen() method).
If you want to implement your own algorithm, you need to override the Processing() method of the
heir class.
Implementation
3496
Standard Library
//+------------------------------------------------------------------+
//| 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 reverse the position
if(CheckReverse()) return(true);
//--- check the possibility of closing the position/delete pending orders
if(!CheckClose())
{
//--- check the possibility of modifying the position
if(CheckTrailingStop()) return(true);
//--- return without operations
return(false);
}
}
//--- check if placed pending orders
int total=OrdersTotal();
if(total!=0)
{
for(int i=total-1;i>=0;i--)
{
m_order.SelectByIndex(i);
if(m_order.Symbol()!=m_symbol.Name()) continue;
if(m_order.OrderType()==ORDER_TYPE_BUY_LIMIT || m_order.OrderType()==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);
}
}
//--- check the possibility of opening a position/setting pending order
if(CheckOpen()) return(true);
//--- return without operations
return(false);
}
3497
Standard Library
CheckOpen
Checks conditions to open position.
virtual bool CheckOpen()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to open long (CheckOpenLong()) and short (CheckOpenShort()) positions.
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);
}
3498
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to open long position (CheckOpenLong() method of Signal object) and opens
long position (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=EMPTY_VALUE;
double
sl=0.0;
double
tp=0.0;
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);
}
3499
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to open short position (CheckOpenShort() method of Signal object) and opens a
short position (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=EMPTY_VALUE;
double
sl=0.0;
double
tp=0.0;
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);
}
3500
Standard Library
OpenLong
Opens a long position.
virtual bool OpenLong(
double
price,
// price
double
sl,
// Stop Loss
double
tp
// Take Profit
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
It gets trading volume (LotOpenLong(...) method) and opens a long position (Buy() method of Trade
object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+
//| Long position open or limit/stop order set
|
//| INPUT: price - price,
|
//|
sl
- stop loss,
|
//|
tp
- take profit.
|
//| OUTPUT: true-if trade operation processed, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::OpenLong(double price,double sl,double tp)
{
if(price==EMPTY_VALUE) return(false);
//--- 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));
}
3501
Standard Library
OpenShort
Opens a short position.
virtual bool OpenShort(
double
price,
// price
double
sl,
// Stop Loss
double
tp
// Take Profit
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
It gets trading volume (LotOpenShort() method) and opens a 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: price - price,
|
//|
sl
- stop loss,
|
//|
tp
- take profit.
|
//| OUTPUT: true-if trade operation successful, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::OpenShort(double price,double sl,double tp)
{
if(price==EMPTY_VALUE) return(false);
//--- 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));
}
3502
Standard Library
CheckReverse
Checks conditions to reverse opened position.
virtual bool CheckReverse()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to reverse long (CheckReverseLong()) and short (CheckReverseShort())
positions.
Implementation
//+------------------------------------------------------------------+
//| Check for position reverse
|
//| INPUT: no.
|
//| OUTPUT: true-if trade operation processed, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::CheckReverse()
{
if(m_position.PositionType()==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);
}
3503
Standard Library
CheckReverseLong
Checks conditions to reverse long position.
virtual bool CheckReverseLong()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to reverse long position (CheckReverseLong() method of Signal object) and
perform reverse operation of the current long position (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=EMPTY_VALUE;
double
sl=0.0;
double
tp=0.0;
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);
}
3504
Standard Library
CheckReverseShort
Checks conditions to reverse short position.
virtual bool CheckReverseLong()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks conditions to reverse short position (CheckReverseShort() method of Signal object) and
perform reverse operation of the current short position (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=EMPTY_VALUE;
double
sl=0.0;
double
tp=0.0;
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);
}
3505
Standard Library
ReverseLong
Performs reverse operation of long position.
virtual bool ReverseLong(
double
price,
// price
double
sl,
// Stop Loss
double
tp
// Take Profit
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
It gets the position reverse volume (LotReverse() method) and reverses a long position (Sell()
method of Trade object) if trading volume is not equal to 0.
In the "hedging" mode of position accounting, position reversal is performed as the closure of the
existing position and opening of a new opposite one with the remaining volume.
Implementation
3506
Standard Library
//+------------------------------------------------------------------+
//| 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)
{
if(price==EMPTY_VALUE)
return(false);
//--- get lot for reverse
double lot=LotReverse(sl);
//--- check lot
if(lot==0.0)
return(false);
//--bool result=true;
if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
{
//--- first close existing position
lot-=m_position.Volume();
result=m_trade.PositionCloseByTicket(m_position.Identifier());
}
if(result)
result=m_trade.Sell(lot,price,sl,tp);
//--return(result);
}
3507
Standard Library
ReverseShort
Performs reverse operation of short position.
virtual bool ReverseShort(
double
price,
// price
double
sl,
// Stop Loss
double
tp
// Take Profit
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
It gets position reverse volume (LotReverse(...) method) and perform trade operation of the short
position reverse (Buy() method of Trade object) if trading volume is not equal to 0.
In the "hedging" mode of position accounting, position reversal is performed as the closure of the
existing position and opening of a new opposite one with the remaining volume.
Implementation
3508
Standard Library
//+------------------------------------------------------------------+
//| Short 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)
{
if(price==EMPTY_VALUE)
return(false);
//--- get lot for reverse
double lot=LotReverse(sl);
//--- check lot
if(lot==0.0)
return(false);
//--bool result=true;
if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
{
//--- first close existing position
lot-=m_position.Volume();
result=m_trade.PositionCloseByTicket(m_position.Identifier());
}
if(result)
result=m_trade.Sell(lot,price,sl,tp);
//--return(result);
}
3509
Standard Library
CheckClose
Checks conditions to close position.
virtual bool CheckClose()
Return Value
true if trade operation has been executed, otherwise false.
Note
1. It checks Expert Advisor Stop Out conditions (CheckClose() method of money management
object). If condition is satisfied, it closes the position and deletes all orders (CloseAll()) and
exits.
2. It checks conditions to close long or short position (CheckCloseLong() or CheckCloseShort()
methods) and if position is closed, it deletes all orders (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.PositionType()==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);
}
3510
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks conditions to close long position (CheckCloseLong() method of Signal object) and if they
are satisfied, it closes the opened position (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=EMPTY_VALUE;
//--- check for long close operations
if(m_signal.CheckCloseLong(price))
return(CloseLong(price));
//--- return without operations
return(false);
}
3511
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks conditions to close short position (CheckCloseShort() method of Signal object) and if they
are satisfied, it closes the position ( 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=EMPTY_VALUE;
//--- check for short close operations
if(m_signal.CheckCloseShort(price))
return(CloseShort(price));
//--- return without operations
return(false);
}
3512
Standard Library
CloseAll
It performs partial of full position closing.
virtual bool CloseAll(
double
lot
// lot
Parameters
lot
[in] Number of lots to reduce the position.
Return Value
true if trade operation has been executed, otherwise false.
Note
In the "netting" mode, a position is closed using the CExpertTrade::Buy or CExpertTrade::Sell
methods. In the "hedging" mode, the CTrade::PositionCloseByTicket method is used. The
DeleteOrders() method is used to delete orders.
Implementation
//+------------------------------------------------------------------+
//| Position close and orders delete
|
//| INPUT: lot - volume for close.
|
//| OUTPUT: true-if trade operation processed, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::CloseAll(double lot)
{
bool result=false;
//--- check for close operations
if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
result=m_trade.PositionCloseByTicket(m_position.Identifier());
else
{
if(m_position.PositionType()==POSITION_TYPE_BUY)
result=m_trade.Sell(lot,0,0,0);
else
result=m_trade.Buy(lot,0,0,0);
}
result|=DeleteOrders();
//--return(result);
}
3513
Standard Library
Close
Closes the opened position.
virtual bool Close()
Return Value
true if trade operation has been executed, otherwise false.
Note
Closes the position (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()));
}
3514
Standard Library
CloseLong
Closes the long position.
virtual bool CloseLong(
double
price
// price
Parameters
price
[in] Price.
Return Value
true if trade operation has been executed, otherwise false.
Note
In the "netting" mode, a position is closed using the CExpertTrade::Buy or CExpertTrade::Sell
methods. In the "hedging" mode, the CTrade::PositionCloseByTicket method is used.
Implementation
//+------------------------------------------------------------------+
//| Long position close
|
//| INPUT: price - price for close.
|
//| OUTPUT: true-if trade operation processed, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::CloseLong(double price)
{
bool result=false;
//--if(price==EMPTY_VALUE)
return(false);
if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
result=m_trade.PositionCloseByTicket(m_position.Identifier());
else
result=m_trade.Sell(m_position.Volume(),price,0,0);
//--return(result);
}
3515
Standard Library
CloseShort
Closes the short position.
virtual bool CloseShort(
double
price
// price
Parameters
price
[in] Price.
Return Value
true if trade operation has been executed, otherwise false.
Note
In the "netting" mode, a position is closed using the CExpertTrade::Buy or CExpertTrade::Sell
methods. In the "hedging" mode, the CTrade::PositionCloseByTicket method is used.
Implementation
//+------------------------------------------------------------------+
//| Short position close
|
//| INPUT: price - price for close.
|
//| OUTPUT: true-if trade operation successful, false otherwise.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::CloseShort(double price)
{
bool result=false;
//--if(price==EMPTY_VALUE)
return(false);
if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
result=m_trade.PositionCloseByTicket(m_position.Identifier());
else
result=m_trade.Buy(m_position.Volume(),price,0,0);
//--return(result);
}
3516
Standard Library
CheckTrailingStop
It checks Trailing Stop conditions of the opened position.
virtual bool CheckTrailingStop()
Return Value
true if any trade operation has been executed, otherwise false.
Note
It checks Trailing Stop conditions of the opened
CheckTrailingStopShort() for long and short positions).
position
(CheckTrailingStopLong()
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.PositionType()==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);
}
or
3517
Standard Library
CheckTrailingStopLong
It checks Trailing Stop conditions of the opened long position.
virtual bool CheckTrailingStopLong()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks Trailing Stop conditions of the opened long position (CheckTrailingStopLong(...) method of
Expert Trailing object). If conditions are satisfied, it modifies the position parameters
(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);
}
3518
Standard Library
CheckTrailingStopShort
It checks Trailing Stop conditions of the opened short position.
virtual bool CheckTrailingStopShort()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks Trailing Stop conditions of the opened short position (CheckTrailingStopShort(...) method
of Expert Trailing object). If conditions are satisfied, it modifies the position parameters
(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);
}
3519
Standard Library
TrailingStopLong
It modifies parameters of the opened long position.
virtual bool TrailingStopLong(
double
sl,
// Stop Loss
double
tp,
// Take Profit
Parameters
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
The function modifies parameters of the opened long position (PositionModify(...) method of
CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Trailing stop/profit long position
|
//| INPUT: sl - new stop loss,
|
//|
tp - new take profit.
|
//| 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));
}
3520
Standard Library
TrailingStopShort
It modifies parameters of the opened short position.
virtual bool TrailingStopLong(
double
sl,
// Stop Loss
double
tp,
// Take Profit
Parameters
sl
[in] Stop Loss price.
tp
[in] Take Profit price.
Return Value
true if trade operation has been executed, otherwise false.
Note
The function modifies parameters of the opened short position (PositionModify(...) method of
CTrade class object).
Implementation
//+------------------------------------------------------------------+
//| Trailing stop/profit short position
|
//| INPUT: sl - new stop loss,
|
//|
tp - new take profit.
|
//| 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));
}
3521
Standard Library
CheckTrailingOrderLong
Checks Trailing Stop conditions of Buy Limit/Stop Pending order.
virtual bool CheckTrailingOrderLong()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks Trailing Stop conditions for buy limit/stop pending order (CheckTrailingOrderLong()
method of Trade Signals object) and modifies the order parameters if necessary
(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(m_order.PriceOpen()-price));
//--- return without operations
return(false);
}
3522
Standard Library
CheckTrailingOrderShort
It checks Trailing Stop conditions of Sell Limit/Stop pending order.
virtual bool CheckTrailingOrderShort()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks Trailing Stop conditions for sell limit/stop pending order (CheckTrailingOrderShort()
method of Trade Signals object) and modifies the order parameters if necessary
(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(m_order.PriceOpen()-price));
//--- return without operations
return(false);
}
3523
Standard Library
TrailingOrderLong
It modifies parameters of Buy Limit/Stop Pending order.
virtual bool TrailingOrderLong(
double
delta
// delta
Parameters
delta
[in] Price delta.
Return Value
true if trade operation has been executed, otherwise false.
Note
It modifies parameters of Buy Limit/Stop Pending order (OrderModify(...) method of CTrade class
object).
Implementation
//+------------------------------------------------------------------+
//| Trailing long limit/stop order
|
//| INPUT: delta - price change.
|
//| 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()));
}
3524
Standard Library
TrailingOrderShort
It modifies parameters of Sell Limit/Stop Pending order.
virtual bool TrailingOrderShort(
double
delta
// delta
Parameters
delta
[in] Price delta.
Return Value
true if trade operation has been executed, otherwise false.
Note
It modifies parameters of Sell Limit/Stop Pending order (OrderModify(...) method of CTrade class
object).
Implementation
//+------------------------------------------------------------------+
//| Trailing short limit/stop order
|
//| INPUT: delta - price change.
|
//| 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()));
}
3525
Standard Library
CheckDeleteOrderLong
It checks conditions to delete Buy Limit/Stop pending order.
virtual bool CheckDeleteOrderLong()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks the order expiration time. It checks conditions to delete the Buy Limit/Stop pending order
(CheckCloseLong(...) method of Signal class object) and deletes the order if condition is satisfied
( DeleteOrderLong() method).
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);
}
3526
Standard Library
CheckDeleteOrderShort
It checks conditions to delete Sell Limit/Stop pending order.
virtual bool CheckDeleteOrderShort()
Return Value
true if trade operation has been executed, otherwise false.
Note
It checks the order expiration time. It checks conditions to delete the Sell Limit/Stop pending order
(CheckCloseShort(...) method of Signal class object) and deletes the order if condition is satisfied
(DeleteOrderShort() method).
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);
}
3527
Standard Library
DeleteOrders
Deletes all orders.
virtual bool DeleteOrders()
Return Value
true if trade operation has been executed, otherwise false.
Note
It deletes all orders (DeleteOrder() for all orders).
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);
}
3528
Standard Library
DeleteOrder
Deletes the Limit/Stop Pending order.
virtual bool DeleteOrder()
Return Value
true if trade operation has been executed, otherwise false.
Note
It deletes the Limit/Stop Pending order (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()));
}
3529
Standard Library
DeleteOrderLong
Deletes the Buy Limit/Stop Pending order.
virtual bool DeleteOrderLong()
Return Value
true if trade operation has been executed, otherwise false.
Note
It deletes Buy Limit/Stop Pending order (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()));
}
3530
Standard Library
DeleteOrderShort
Deletes the Sell Limit/Stop Pending order.
virtual bool DeleteOrderShort()
Return Value
true if trade operation has been executed, otherwise false.
Note
It deletes the Sell Limit/Stop pending order (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()));
}
3531
Standard Library
LotOpenLong
Gets trade volume for buy operation.
double LotOpenLong(
double
price,
// price
double
sl
// Stop Loss
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume (in lots) for buy operation.
Note
It gets trade volume for buy operation (CheckOpenLong(...) method of money management object).
Implementation
//+------------------------------------------------------------------+
//| Method of getting the lot for open long position.
|
//| INPUT: price - price,
|
//|
sl
- stop loss.
|
//| OUTPUT: lot for open.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
double CExpert::LotOpenLong(double price,double sl)
{
return(m_money.CheckOpenLong(price,sl));
}
3532
Standard Library
LotOpenShort
Gets trade volume for sell operation.
double LotOpenShort(
double
price,
// price
double
sl
// Stop Loss
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume (in lots) for sell operation.
Note
It gets trade volume for sell operation (CheckOpenShort(...) method of money management object).
Implementation
//+------------------------------------------------------------------+
//| Method of getting the lot for open short position.
|
//| INPUT: price - price,
|
//|
sl
- stop loss.
|
//| OUTPUT: lot for open.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
double CExpert::LotOpenShort(double price,double sl)
{
return(m_money.CheckOpenShort(price,sl));
}
3533
Standard Library
LotReverse
Gets trade volume for position reverse.
double LotReverse(
double
sl
// Stop Loss
Parameters
sl
[in] Stop Loss price.
Return Value
Trade volume (in lots) for position reverse operation.
Note
It gets trade volume for position reverse operation (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));
}
3534
Standard Library
PrepareHistoryDate
Sets starting date for tracking of trade history.
void PrepareHistoryDate()
Note
The trade history tracking period is set from the beginning of the month (but not less than one day).
3535
Standard Library
HistoryPoint
Creates a 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 recursion.
Note
It saves the amount of positions, orders, deals and historical orders.
3536
Standard Library
CheckTradeState
Compares the current state with the saved one and calls the corresponding event handler.
bool CheckTradeState()
Return Value
true if event has been handled, otherwise - false.
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.
3537
Standard Library
WaitEvent
Sets the event waiting flag.
void WaitEvent(
ENUM_TRADE_EVENTS
event
// flag
Parameters
event
[in] Flag with events to set (ENUM_TRADE_EVENTS enumeration).
Return Value
None.
Event flags
//--- flags of expected events
enum ENUM_TRADE_EVENTS
{
TRADE_EVENT_NO_EVENT
=0,
TRADE_EVENT_POSITION_OPEN
=0x1,
TRADE_EVENT_POSITION_VOLUME_CHANGE=0x2,
TRADE_EVENT_POSITION_MODIFY
=0x4,
TRADE_EVENT_POSITION_CLOSE
=0x8,
TRADE_EVENT_POSITION_STOP_TAKE
=0x10,
TRADE_EVENT_ORDER_PLACE
=0x20,
TRADE_EVENT_ORDER_MODIFY
=0x40,
TRADE_EVENT_ORDER_DELETE
=0x80,
TRADE_EVENT_ORDER_TRIGGER
=0x100
};
//
//
//
//
//
//
//
//
//
//
no expected events
flag of expecting the "opening of position" eve
flag of expecting of the "modification of posit
flag of expecting of the "modification of stop
flag of expecting of the "closing of position"
flag of expecting of the "triggering of stop or
flag of expecting of the "placing of pending or
flag of expecting of the "modification of pendi
flag of expecting of the "deletion of pending o
flag of expecting of the "triggering of pending
3538
Standard Library
NoWaitEvent
Resets the event waiting flag.
void NoWaitEvent(
ENUM_TRADE_EVENTS
event
// flag
Parameters
event
[in] Flag with events to reset (ENUM_TRADE_EVENTS enumeration).
Return Value
None.
Event flags
//--- flags of expected events
enum ENUM_TRADE_EVENTS
{
TRADE_EVENT_NO_EVENT
=0,
TRADE_EVENT_POSITION_OPEN
=0x1,
TRADE_EVENT_POSITION_VOLUME_CHANGE=0x2,
TRADE_EVENT_POSITION_MODIFY
=0x4,
TRADE_EVENT_POSITION_CLOSE
=0x8,
TRADE_EVENT_POSITION_STOP_TAKE
=0x10,
TRADE_EVENT_ORDER_PLACE
=0x20,
TRADE_EVENT_ORDER_MODIFY
=0x40,
TRADE_EVENT_ORDER_DELETE
=0x80,
TRADE_EVENT_ORDER_TRIGGER
=0x100
};
//
//
//
//
//
//
//
//
//
//
no expected events
flag of expecting the "opening of position" eve
flag of expecting of the "modification of posit
flag of expecting of the "modification of stop
flag of expecting of the "closing of position"
flag of expecting of the "triggering of stop or
flag of expecting of the "placing of pending or
flag of expecting of the "modification of pendi
flag of expecting of the "deletion of pending o
flag of expecting of the "triggering of pending
3539
Standard Library
TradeEventPositionStopTake
Event handler of the "Position Stop Loss/Take Profit triggered" event.
virtual bool TradeEventPositionStopTake()
Return Value
The CExpert class method does nothing and always returns true.
3540
Standard Library
TradeEventOrderTriggered
Event handler of the "Pending Order triggered" event.
virtual bool TradeEventOrderTriggered()
Return Value
The CExpert class method does nothing and always returns true.
3541
Standard Library
TradeEventPositionOpened
Event handler of the "Position opened" event.
virtual bool TradeEventPositionOpened()
Return Value
The CExpert class method does nothing and always returns true.
3542
Standard Library
TradeEventPositionVolumeChanged
Event handler of the "Position volume changed" event.
virtual bool TradeEventPositionVolumeChanged()
Return Value
The CExpert class method does nothing and always returns true.
3543
Standard Library
TradeEventPositionModified
Event handler of the "Position modified" event.
virtual bool TradeEventPositionModified()
Return Value
The CExpert class method does nothing and always returns true.
3544
Standard Library
TradeEventPositionClosed
Event handler of the "Position closed" event.
virtual bool TradeEventPositionClosed()
Return Value
The CExpert class method does nothing and always returns true.
3545
Standard Library
TradeEventOrderPlaced
Event handler of the "Pending order placed" event.
virtual bool TradeEventOrderPlaced()
Return Value
The CExpert class method does nothing and always returns true.
3546
Standard Library
TradeEventOrderModified
Event handler of the "Pending order modified" event.
virtual bool TradeEventOrderModified()
Return Value
The CExpert class method does nothing and always returns true.
3547
Standard Library
TradeEventOrderDeleted
Event handler of the "Pending order deleted" event.
virtual bool TradeEventOrderDeleted()
Return Value
The CExpert class method does nothing and always returns true.
3548
Standard Library
TradeEventNotIdentified
Event handler of the non-identified event.
virtual bool TradeEventNotIdentified()
Return Value
The CExpert class method does nothing and always returns true.
Note
Note that several trade events can arrive, in such cases it's difficult to identify them.
3549
Standard Library
TimeframeAdd
Add a timeframe for tracking.
void TimeframeAdd(
ENUM_TIMEFRAMES
period
// timeframe
Parameters
period
[in] Timeframe (ENUM_TIMEFRAMES enumeration).
Return Value
None.
3550
Standard Library
TimeframesFlags
The method returns the flag indicating the timeframes with a new bar.
int TimeframesFlags(
MqlDateTime&
time
Parameters
time
[in] Variable of MqlDateTime type for new time, passed by reference.
Return Value
It returns the flag, that indicates timeframes with a new bar.
3551
Standard Library
SelectPosition
Selects a position to work with.
void
SelectPosition()
Return Value
No.
Implementation
//+------------------------------------------------------------------+
//| Position select
|
//| INPUT: no.
|
//| OUTPUT: no.
|
//| REMARK: no.
|
//+------------------------------------------------------------------+
bool CExpert::SelectPosition(void)
{
bool res=false;
//--if(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
res=m_position.SelectByMagic(m_symbol.Name(),m_magic);
else
res=m_position.Select(m_symbol.Name());
//--return(res);
}
3552
Standard Library
CExpertSignal
CExpertSignal is a base class for trading signals, it does nothing (except CheckReverseLong() and
CheckReverseShort() methods) but provides the interfaces.
How to use it:
1. Prepare an algorithm for trading signals;
2. Create your own trading signal class, inherited from CExpertSignal class;
3. Override the virtual methods in your class with your own algorithms.
You can find an examples of trading signal classes in the Expert\Signal\ folder.
Description
CExpertSignal is a base class for implementation of trading signal algorithms.
Declaration
class CExpertSignal : public CExpertBase
Title
#include <Expert\ExpertSignal.mqh>
Class Methods
Initialization
virtual InitIndicators
virtual ValidationSettings
virtual AddFilter
UsedSeries
Parameters Setting
Weight
PatternsUsage
General
Ignore
Invert
ThresholdOpen
ThresholdClose
PriceLevel
3553
Standard Library
StopLevel
TakeLevel
Expiration
Magic
virtual CheckCloseLong
virtual CheckOpenShort
virtual CheckCloseShort
virtual CheckReverseLong
virtual CheckReverseShort
virtual OpenShortParams
virtual CloseLongParams
virtual CloseShortParams
virtual CheckTrailingOrderShort
virtual ShortCondition
virtual Direction
3554
Standard Library
BasePrice
Sets base price level.
void BasePrice(
double
value
// new value
Parameters
value
[in] New value of Base price level.
Return Value
None.
3555
Standard Library
UsedSeries
Gets the flags of the timeseries used.
int BasePrice()
Return Value
Flags of the used timeseries (if the symbol/timeframe corresponds to the working symbol/
timeframe), otherwise 0.
3556
Standard Library
Weight
Sets new value of "Weight" parameter.
void Weight(
double
value
// new value
Parameters
value
[in] New value of "Weight".
Return Value
None.
3557
Standard Library
PatternUsage
Sets new value of "PatternsUsage" parameter.
void PatternUsage(
double
value
// new value
Parameters
value
[in] New value of "PatternsUsage".
Return Value
None.
3558
Standard Library
General
Sets new value of "General" parameter.
void General(
int
value
// new value
Parameters
value
[in] New value of "General".
Return Value
None.
3559
Standard Library
Ignore
Sets new value of "Ignore" parameter.
void Ignore(
long
value
// new value
Parameters
value
[in] New value of "Ignore".
Return Value
None.
3560
Standard Library
Invert
Sets new value of "Invert" parameter.
void Invert(
long
value
// new value
Parameters
value
[in] New value of "Invert".
Return Value
None.
3561
Standard Library
ThresholdOpen
Sets new value of "ThresholdOpen" parameter.
void ThresholdOpen(
long
value
// new value
Parameters
value
[in] New value of "ThresholdOpen".
Return Value
None.
Note
The range of "ThresholdOpen" parameter is from 0 to 100. Used when "voting" to open position.
3562
Standard Library
ThresholdClose
Sets new value of "ThresholdClose" parameter.
void ThresholdOpen(
long
value
// new value
Parameters
value
[in] New value of "ThresholdClose".
Return Value
None.
Note
The range of "ThresholdClose" parameter is from 0 to 100. Used when "voting" to close position.
3563
Standard Library
PriceLevel
Sets new value of "PriceLevel" parameter.
void PriceLevel(
double
value
// new value
Parameters
value
[in] New value of "PriceLevel".
Return Value
None.
Note
The value of "PriceLevel" is defined in price level units. The numerical values of price level unit is
returned by PriceLevelUnit() method. The "PriceLevel" is used to define the open price relative to
the base price.
3564
Standard Library
StopLevel
Sets new value of "StopLevel" parameter.
void StopLevel(
double
value
// new value
Parameters
value
[in] New value of "StopLevel".
Return Value
None.
Note
The value of "StopLevel" is defined in price level units. The numerical values of price level unit is
returned by PriceLevelUnit() method. The "StopLevel" is used to define the Stop Loss price relative
to the open price.
3565
Standard Library
TakeLevel
Sets new value of "TakeLevel" parameter.
void TakeLevel(
double
value
// new value
Parameters
value
[in] New value of "TakeLevel".
Return Value
None.
Note
The value of "TakeLevel" is defined in price level units. The numerical values of price level unit is
returned by PriceLevelUnit() method. The "TakeLevel" is used to define the Take Profit price
relative to the open price.
3566
Standard Library
Expiration
Sets the value of "Expiration" parameter.
void Expiration(
int
value
// new value
Parameters
value
[in] New value of "Expiration".
Return Value
None.
Note
The value of "Expiration" parameter is defined in bars. It is used as Expiration time for Pending
Orders (when trading using pending orders).
3567
Standard Library
Magic
Sets the value of "Magic" parameter.
void Magic(
int
value
// new value
Parameters
value
[in] New value of "Magic" (Expert Advisor ID).
Return Value
None.
3568
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
3569
Standard Library
InitIndicators
Initializes all indicators and time series.
virtual bool InitIndicators(
CIndicators* indicators
// pointer
Parameters
indicators
[in] Pointer to collection of indicators and timeseries.
Return Value
true if successful, otherwise false.
Note
The timeseries are initialized only if the object uses the symbol or timeframe, different from the
symbol or timeframe, defined at initialization.
3570
Standard Library
AddFilter
Adds a filter to the composite signal.
virtual bool InitIndicators(
CExpertSignal* filter
// pointer
Parameters
indicators
[in] Pointer to filter object.
Return Value
true if successful, otherwise false.
3571
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3572
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3573
Standard Library
OpenLongParams
Sets parameters to open long position.
virtual bool OpenLongParams(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if successful, otherwise false.
3574
Standard Library
OpenShortParams
Sets parameters to open short position.
virtual bool OpenShortParams(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if successful, otherwise false.
3575
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong(
double& price
// price
Parameters
price
[in][out] Variable for close price, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3576
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort(
double& price
// price
Parameters
price
[in][out] Variable for close price, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3577
Standard Library
CloseLongParams
Sets parameters to close long position.
virtual bool CloseLongParams(
double&
price
// price
Parameters
price
[in][out] Variable for close price, passed by reference.
Return Value
true if successful, otherwise false.
3578
Standard Library
CloseShortParams
Sets parameters to close short position.
virtual bool CloseShortParams(
double&
price
// price
Parameters
price
[in][out] Variable for close price, passed by reference.
Return Value
true if successful, otherwise false.
3579
Standard Library
CheckReverseLong
Checks conditions of long position reversal.
virtual bool CheckReverseLong(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3580
Standard Library
CheckReverseShort
Checks conditions of short position reversal.
virtual bool CheckReverseShort(
double&
price,
// price
double&
sl,
// Stop Loss
double&
tp,
// Take Profit
datetime& expiration
// expiration
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 expiration time, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
3581
Standard Library
CheckTrailingOrderLong
Checks conditions to modify parameters of Buy Pending order.
virtual bool CheckTrailingOrderLong(
COrderInfo*
order,
// order
double&
price
// price
Parameters
order
[in] Pointer to COrderInfo class object.
price
[in][out] Variable for Stop Loss price.
Return Value
true if condition is satisfied, otherwise false.
3582
Standard Library
CheckTrailingOrderShort
Checks conditions to modify parameters of Sell Pending order.
virtual bool CheckTrailingOrderShort(
COrderInfo*
order,
// order
double&
price
// price
Parameters
order
[in] Pointer to COrderInfo class object.
price
[in][out] Variable for Stop Loss price.
Return Value
true if condition is satisfied, otherwise false.
3583
Standard Library
LongCondition
Checks conditions to open long position.
virtual int LongCondition()
Return Value
If the conditions are satisfied, it returns the value from 1 to 100 (depending on "strength" of a
signal). If there isn't a signal to open long position, it returns 0.
Note
The LongCondition() method of a base class has no implementation of checking of conditions to
open long position and always returns 0.
3584
Standard Library
ShortCondition
Checks conditions to open short position.
virtual int ShortCondition()
Return Value
If the conditions are satisfied, it returns the value from 1 to 100 (depending on "strength" of a
signal). If there isn't a signal to open short position, it returns 0.
Note
The ShortCondition() method of a base class has no implementation of checking of conditions to
open short position and always returns 0.
3585
Standard Library
Direction
Returns the value of "weighted" direction.
virtual double Direction()
Return Value
It returns the value>0 when upward direction (probably) and the returned value<0 when downward
direction. The absolute value depends on the "strength" of a signal.
Note
If the filters are used, the result will depend on the filters.
3586
Standard Library
CExpertTrailing
CExpertTrailing is a base class for trailing algorithms, it does nothing but provides the interfaces.
How to use it:
1. Prepare an algorithm for trailing;
2. Create your own trailing class, inherited from CExpertTrailing class;
3. Override the virtual methods in your class with your own algorithms.
You can find an examples of trailing classes in the Expert\Trailing\ folder.
Description
CExpertTrailing is a base class for implementation of trailing stop algoritms.
Declaration
class CExpertTrailing : public CExpertBase
Title
#include <Expert\ExpertTrailing.mqh>
Class Methods
Checking of Trailing Stop Conditions
virtual CheckTrailingStopLong
virtual CheckTrailingStopShort
3587
Standard Library
CheckTrailingStopLong
Checks conditions to modify parameters of the long position.
virtual bool CheckTrailingStopLong(
CPositionInfo* position,
// pointer
double&
sl,
// Stop Loss
double&
tp
// Take Profit
Parameters
position
[in] Pointer to CPositionInfo class object.
sl
[in][out] Variable for Stop Loss price, passed by reference.
tp
[in][out] Variable for Take Profit price, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
Note
The CheckTrailingStopLong(...) method of the base class always returns false.
3588
Standard Library
CheckTrailingStopShort
Checks conditions to modify parameters of the short position.
virtual bool CheckTrailingStopShort(
CPositionInfo* position,
// pointer
double&
sl,
// Stop Loss
double&
tp
// Take Profit
Parameters
position
[in] Pointer to CPositionInfo class object.
sl
[in][out] Variable for Stop Loss price, passed by reference.
tp
[in][out] Variable for Take Profit price, passed by reference.
Return Value
true if condition is satisfied, otherwise false.
Note
The CheckTrailingStopShort(...) method of the base class always returns false.
3589
Standard Library
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
Access to Protected Data
Percent
Initialization
virtual ValidationSettings
virtual CheckOpenShort
virtual CheckReverse
virtual CheckClose
3590
Standard Library
Percent
Sets the value of "Risk percent" parameter.
void Percent(
double percent
// risk percent
Parameters
percent
[in] Risk percent.
Return Value
None.
3591
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
The ValidationSettings() method of the base class always returns true.
3592
Standard Library
CheckOpenLong
Gets the volume for long position.
virtual double CheckOpenLong(
double price,
// price
double sl
// Stop Loss
Parameters
price
[in] Opening price of long position.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
3593
Standard Library
CheckOpenShort
Gets the volume for short position.
virtual double CheckOpenShort(
double price,
// price
double sl
// Stop Loss
Parameters
price
[in] Opening price for short position.
sl
[in] Stop Loss price.
Return Value
Trade volume for short position.
3594
Standard Library
CheckReverse
Gets the volume for reverse of the position.
virtual double CheckReverse(
CPositionInfo* position,
// pointer
double
// Stop Loss
sl
Parameters
position
[in] Pointer to CPositionInfo class object.
sl
[in] Stop Loss price.
Return Value
Volume for reverse of the position.
3595
Standard Library
CheckClose
Checks conditions to close the opened position.
virtual double CheckClose()
Return Value
true if condition is satisfied, otherwise false.
3596
Standard Library
values of an indicator).
Each market model has a significance that may vary with the range of 1 to 100. The higher is the
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
3597
Standard Library
corresponds to the strength of the best found model.
The forecast of each module is sent to the final "voting" with a weight coefficient of 0 to 1 specified
direction of the forecast movement, and the absolute value characterizes the strength of the signal.
It is calculated as the Arithmetic mean of weighted forecasts of all the modules of signals.
Each generated Expert Advisor has two adjustable settings threshold levels of opening and closing a
position (ThresholdOpen and ThresholdClose) that can be equal to a value in the range of 0 to 100. If
the strength of final signal exceeds a threshold level, a trade operation that corresponds to the sign of
the signal is performed.
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 is
calculated as the Arithmetic 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 Arithmetic 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.
3598
Standard Library
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).
3599
Standard Library
Description of Conditions
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.
3600
Standard Library
Signal
Type
Description of Conditions
The indicator value is below 0 and it falls at the analyzed and at the previous bars.
No
objections
to buying
No
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:
3601
Standard Library
Parameter
Description
Weight
3602
Standard Library
Description of Conditions
For buying
The price has crossed the indicator downwards (the Open price of the analyzed bar
is above the indicator and the Close price is below the indicator) and the indicator
rises (weak signal).
Moving Average crossover. The price has crossed the indicator upwards (the Open
price of the analyzed bar is below the indicator and the Close price is above the
indicator) and the indicator rises (strong signal).
3603
Standard Library
Signal
Type
Description of Conditions
The lower shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is above the indicator, and the Low price is below the
indicator) and the indicator rises (weak signal).
For selling
The price has crossed the indicator upwards (the Open price of the analyzed bar is
below the indicator and the Close price is above the indicator) and the indicator falls
(weak signal).
Moving Average crossover. The price has crossed the indicator downwards (the
Open price of the analyzed bar is above the indicator and the Close price is below
the indicator) and the indicator falls (strong signal).
3604
Standard Library
Signal
Type
Description of Conditions
The upper shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is below the indicator, and the High price is above the
indicator) and the indicator falls (weak signal).
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3605
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
3606
Standard Library
Description of Conditions
For buying
Saucer value of the indicator at the analyzed bar rises, and it fell at the
Crossing the zero line value of the indicator is above 0 at the analyzed bar, and
Divergence the first analyzed bottom of the indicator is shallower than the
previous one, and the corresponding price valley is deeper than the previous one.
3607
Standard Library
Signal
Type
Description of Conditions
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
Crossing the zero line value of the indicator is below 0 at the analyzed bar, and
3608
Standard Library
Signal
Type
Description of Conditions
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.
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3609
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
3610
Standard Library
Description of Conditions
For buying
Reverse the oscillator turned upwards and its value at the analyzed bar is below
0.
Divergence the first analyzed bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
In addition, the oscillator must not rise above the zero level.
For selling
3611
Standard Library
Signal
Type
Description of Conditions
No
objections
to buying
No
objections
to selling
No signals.
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
Weight
PeriodBears
3612
Standard Library
Description of Conditions
For buying
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.
3613
Standard Library
Signal
Type
Description of Conditions
No
objections
to buying
No signals.
No
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
Weight
PeriodBulls
3614
Standard Library
Description of Conditions
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 bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
them is higher than the previous one; and the price formed three corresponding
3615
Standard Library
Signal
Type
Description of Conditions
For selling
Reverse behind the overbought level the oscillator turned downwards and its
value at the analyzed bar is behind the overbought level (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.
3616
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator formed three consequent peaks, each of them
is lower than the previous one; and the price formed three corresponding peaks,
each of them is higher than the previous one.
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3617
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodCCI
Applied
3618
Standard Library
Description of Conditions
For buying
Reverse behind the oversold level the oscillator turned upwards and its value
at the analyzed bar is behind the oversold level (default value is 0.3).
Divergence the first analyzed bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
Double divergence the oscillator form three consequent bottoms, each of them
is higher than the previous one; and the price formed three corresponding
bottoms, and each of them is lower than the previous one.
3619
Standard Library
Signal
Type
Description of Conditions
For selling
Reverse behind the overbought level the oscillator turned downwards and its
value at the analyzed bar is behind the overbought level (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.
3620
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator formed three consequent peaks, each of them
is lower than the previous one; and the price formed three corresponding peaks,
each of them is higher than the previous one.
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3621
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodDeM
3622
Standard Library
Description of Conditions
The price has crossed the indicator downwards (the Open price of the analyzed bar is
above the indicator and the Close price is below the indicator) and the indicator
rises (weak signal).
Moving Average crossover. The price has crossed the indicator upwards (the Open
price of the analyzed bar is below the indicator and the Close price is above the
indicator) and the indicator rises (strong signal).
3623
Standard Library
Signal
Type
Description of Conditions
The lower shadow of the bar has crossed the indicator (the Open and Close prices of
the analyzed bar is above the indicator, and the Low price is below the indicator)
and the indicator rises (weak signal).
For selling
The price has crossed the indicator upwards (the Open price of the analyzed bar is
below the indicator and the Close price is above the indicator) and the indicator falls
(weak signal).
Moving Average crossover. The price has crossed the indicator downwards (the
Open price of the analyzed bar is above the indicator and the Close price is below
the indicator) and the indicator falls (strong signal).
3624
Standard Library
Signal
Type
Description of Conditions
The upper shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is below the indicator, and the High price is above the
indicator) and the indicator falls (weak signal).
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3625
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
3626
Standard Library
Description of Conditions
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.
3627
Standard Library
Signal
Type
Description of Conditions
The price crossed the lower line of the indicator at the analyzed bar.
No
objection
s
to
buying
No signals.
No
objection
s
to
selling
No signals.
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).
3628
Standard Library
Adjustable Parameters
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
Deviation
3629
Standard Library
Description of Conditions
The price has crossed the indicator downwards (the Open price of the analyzed bar
is above the indicator and the Close price is below the indicator) and the indicator
rises (weak signal).
Moving Average crossover. The price has crossed the indicator upwards (the Open
price of the analyzed bar is below the indicator and the Close price is above the
indicator) and the indicator rises (strong signal).
3630
Standard Library
Signal
Type
Description of Conditions
The lower shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is above the indicator, and the Low price is below the indicator)
and the indicator rises (weak signal).
For selling
The price has crossed the indicator upwards (the Open price of the analyzed bar is
below the indicator and the Close price is above the indicator) and the indicator falls
(weak signal).
Moving Average crossover. The price has crossed the indicator downwards (the
Open price of the analyzed bar is above the indicator and the Close price is below
the indicator) and the indicator falls (strong signal).
3631
Standard Library
Signal
Type
Description of Conditions
The upper shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is below the indicator, and the High price is above the
indicator) and the indicator falls (weak signal).
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3632
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
3633
Standard Library
Description of Conditions
For buying
No signals.
For selling
No signals.
No objections to buying
No objections to selling
Adjustable Parameters
This module has the following adjustable parameters:
Parameter
Description
Weight
GoodHourOfDay
BadHoursOfDay
GoodDayOfWeek
3634
Standard Library
Parameter
Description
enabled. If the value is -1, the signals will be
enabled on any day.
BadDaysOfWeek
3635
Standard Library
Description of Conditions
For buying
Reverse the oscillator turned upwards (the oscillator rises at the analyzed bar
Crossover 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
3636
Standard Library
Signal
Type
Description of Conditions
Divergence the first analyzed bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
Double divergence the oscillator form three consequent bottoms, each of them
is higher than the previous one; and the price formed three corresponding
bottoms, and each of them is lower than the previous one.
3637
Standard Library
Signal
Type
Description of Conditions
For selling
Reverse the oscillator turned downwards (the oscillator falls at the analyzed bar
Crossover 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.
3638
Standard Library
Signal
Type
Description of Conditions
Crossing the zero level the main line is below the zero level 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.
3639
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator formed three consequent peaks, each of them
is lower than the previous one; and the price formed three corresponding peaks,
each of them is higher than the previous one.
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3640
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodFast
PeriodSlow
PeriodSignal
Period of smoothing.
Applied
3641
Standard Library
Description of Conditions
The price has crossed the indicator downwards (the Open price of the analyzed bar
is above the indicator and the Close price is below the indicator) and the indicator
rises (weak signal).
Moving Average crossover. The price has crossed the indicator upwards (the Open
price of the analyzed bar is below the indicator and the Close price is above the
indicator) and the indicator rises (strong signal).
3642
Standard Library
Signal
Type
Description of Conditions
The lower shadow of the bar has crossed the indicator (the Open and Close prices of
the analyzed bar is above the indicator, and the Low price is below the indicator)
and the indicator rises (weak signal).
For selling
The price has crossed the indicator upwards (the Open price of the analyzed bar is
below the indicator and the Close price is above the indicator) and the indicator falls
(weak signal).
Moving Average crossover. The price has crossed the indicator downwards (the
Open price of the analyzed bar is above the indicator and the Close price is below
the indicator) and the indicator falls (strong signal).
3643
Standard Library
Signal
Type
Description of Conditions
The upper shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is below the indicator, and the High price is above the
indicator) and the indicator falls (weak signal).
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3644
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
3645
Standard Library
Description of Conditions
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.
No
objections
3646
Standard Library
Signal
Type
Description of Conditions
to buying
No
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
Weight
Step
Maximum
3647
Standard Library
Description of Conditions
For buying
Reverse behind the oversold level the oscillator turned upwards and its value
at the analyzed bar is behind the oversold level (default value is 30).
Failed swing the oscillator rises higher than the previous peak at the analyzed
bar.
Divergence the first analyzed bottom of the oscillator is lower than the previous
one, and the corresponding price bottom is lower than the previous one.
3648
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator form three consequent bottoms, each of them
is higher than the previous one; and the price formed three corresponding
bottoms, and each of them is lower than the previous one.
Head/Shoulders the oscillator formed three consequent bottoms, and the mid
3649
Standard Library
Signal
Type
Description of Conditions
For selling
Reverse behind the overbought level the oscillator turned downwards and its
value at the analyzed bar is behind the overbought level (default value is 70).
Failed swing the oscillator falls lower than the previous bottom at the analyzed
bar.
3650
Standard Library
Signal
Type
Description of Conditions
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.
Double divergence the oscillator formed three consequent peaks, each of them
is lower than the previous one; and the price formed three corresponding peaks,
each of them is higher than the previous one.
3651
Standard Library
Signal
Type
Description of Conditions
Head/Shoulders the oscillator formed three consequent peaks, and the mid one
No
objections
to buying
No
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
3652
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodRSI
Applied
3653
Standard Library
Description of Conditions
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.
No
objections
3654
Standard Library
Signal
Type
Description of Conditions
to buying
No
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
Weight
PeriodRVI
3655
Standard Library
Description of Conditions
For buying
Reverse the oscillator turned upwards (the oscillator rises at the analyzed bar
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 bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
3656
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator form three consequent bottoms, each of them
is higher than the previous one; and the price formed three corresponding
bottoms, and each of them is lower than the previous one.
For selling
Reverse the oscillator turned downwards (the oscillator falls at the analyzed bar
3657
Standard Library
Signal
Type
Description of Conditions
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.
3658
Standard Library
Signal
Type
Description of Conditions
Double divergence the oscillator formed three consequent peaks, each of them
is lower than the previous one; and the price formed three corresponding peaks,
each of them is higher than the previous one.
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3659
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodK
PeriodD
PeriodSlow
Period of slowing.
Applied
3660
Standard Library
Description of Conditions
For buying
Reverse the oscillator turned upwards (the oscillator rises at the analyzed bar
Crossing the zero level the main line is above the zero level at the analyzed bar
Divergence the first analyzed bottom of the oscillator is higher than the
3661
Standard Library
Signal
Type
Description of Conditions
previous one, and the corresponding price bottom is lower than the previous one.
For selling
Reverse the oscillator turned downwards (the oscillator falls at the analyzed bar
Crossing the zero level the main line is below the zero level at the analyzed bar
3662
Standard Library
Signal
Type
Description of Conditions
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.
No
objections
to buying
No
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
3663
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodTriX
Applied
3664
Standard Library
Description of Conditions
The price has crossed the indicator downwards (the Open price of the analyzed bar
is above the indicator and the Close price is below the indicator) and the indicator
rises (weak signal).
Moving Average crossover. The price has crossed the indicator upwards (the Open
price of the analyzed bar is below the indicator and the Close price is above the
indicator) and the indicator rises (strong signal).
3665
Standard Library
Signal
Type
Description of Conditions
The lower shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is above the indicator, and the Low price is below the indicator)
and the indicator rises (weak signal).
For selling
The price has crossed the indicator upwards (the Open price of the analyzed bar is
below the indicator and the Close price is above the indicator) and the indicator falls
(weak signal).
Moving Average crossover. The price has crossed the indicator downwards (the
Open price of the analyzed bar is above the indicator and the Close price is below
the indicator) and the indicator falls (strong signal).
3666
Standard Library
Signal
Type
Description of Conditions
The upper shadow of the bar has crossed the indicator (the Open and Close prices
of the analyzed bar is below the indicator, and the High price is above the
indicator) and the indicator falls (weak signal).
No
objections
to buying
No
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
2000-2016, MetaQuotes Software Corp.
3667
Standard Library
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodMA
Shift
Method
Method of averaging.
Applied
3668
Standard Library
Description of Conditions
For buying
Reverse behind the oversold level the oscillator turned upwards and its value
at the analyzed bar is behind the oversold level (default value is -20).
Divergence the first analyzed bottom of the oscillator is higher than the
previous one, and the corresponding price bottom is lower than the previous one.
For selling
Reverse behind the overbought level the oscillator turned downwards and its
3669
Standard Library
Signal
Type
Description of Conditions
value at the analyzed bar is behind the overbought level (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.
No
objections
to buying
No
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).
Remember that the oscillator Williams Percent Range has a reversed scale. Its maximum value is -100,
3670
Standard Library
and minimum is 0.
Adjustable Parameters
This module has the following adjustable parameters:
Parameter
Description
Weight
PeriodWPR
3671
Standard Library
Description
CTrailingFixedPips
CTrailingMA
CTrailingNone
CTrailingPSAR
3672
Standard Library
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 than the Stop Loss level, it suggests to set a 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
ProfitLevel
virtual ValidationSettings
virtual CheckTrailingStopShort
3673
Standard Library
StopLevel
Sets the value Stop Loss level (in points).
void StopLevel(
int stop_level
Parameters
stop_loss
[in] The value of Stop Loss level (in conventional 2/4-digit points).
Note
If Stop Loss level is equal to 0, the Trailing Stop is not used.
3674
Standard Library
ProfitLevel
Sets the value of Take Profit level (in points).
void ProfitLevel(
int profit_level
Parameters
profit_level
[in] The value of Take Profit level (in conventional 2/4-digit points).
Note
If profit level is equal to 0, the Trailing Stop is not used.
3675
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
The function checks Take Profit and Stop Loss levels. The correct values are 0 and values greater
than the minimal indention in points from the current close price to place Stop orders.
3676
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
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, otherwise 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.
3677
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
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, otherwise 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.
3678
Standard Library
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
Shift
Method
Applied
virtual InitIndicators
virtual ValidationSettings
virtual CheckTrailingStopShort
3679
Standard Library
Period
Sets period of moving average.
void Period(
int period
// Smoothing period
Parameters
period
[in] Period of moving average.
3680
Standard Library
Shift
Sets shift of moving average.
void Shift(
int shift
// Shift
Parameters
shift
[in] Shift of moving average.
3681
Standard Library
Method
Sets smoothing method of moving average.
void Method(
ENUM_MA_METHOD method
// Smoothing method
Parameters
method
[in] Smoothing method of moving average indicator.
3682
Standard Library
Applied
Sets applied price of moving average.
void Applied(
ENUM_APPLIED_PRICE applied
// Applied price
Parameters
applied
[in] Applied price of moving average.
3683
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators(
CIndicators* indicators
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Return Value
true if successful, otherwise false.
3684
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
The function checks the period of moving average, the correct values are positive.
3685
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
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, otherwise 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.
3686
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
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, otherwise 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.
3687
Standard Library
CTrailingNone
CTrailingNone is a stub 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 algorithm. The methods of checking Trailing
Stop conditions always return false.
Declaration
class CTrailingNone: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingNone.mqh>
Class Methods
Check Trailing Methods
virtual CheckTrailingStopLong
Trailing
Stop
virtual CheckTrailingStopShort
Trailing
Stop
3688
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
The function always returns false.
3689
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort(
CPositionInfo* position,
double&
sl,
double&
tp
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
The function always returns false.
3690
Standard Library
CTrailingPSAR
CTrailingPSAR is a class with implementation of Trailing Stop algorithm based on the values 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
Maximum
virtual InitIndicators
virtual CheckTrailingStopShort
3691
Standard Library
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.
3692
Standard Library
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.
3693
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators(
CIndicators* indicators
Parameters
indicators
[in] Pointer to indicators and time series collection (CExpert class member).
Return Value
true if successful, otherwise false.
3694
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong(
CPositionInfo* position,
// Pointer
double&
sl,
// Link
double&
tp
// Link
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
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, otherwise 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.
3695
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort(
CPositionInfo* position,
// Pointer
double&
sl,
// Link
double&
tp
// Link
Parameters
position
[in] Pointer to CPositionInfo object.
sl
[in][out] Variable for Stop Loss price.
tp
[in][out] Variable for Take Profit price.
Return Value
true if conditions are satisfied, otherwise false.
Note
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, otherwise 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.
3696
Standard Library
Description
CMoneyFixedLot
CMoneyFixedMargin
CMoneyFixedRisk
CMoneyNone
CMoneySizeOptimized
3697
Standard Library
CMoneyFixedLot
CMoneyFixedLot is the class designed to implement 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
virtual ValidationSettings
virtual CheckOpenShort
3698
Standard Library
Lots
Sets trading volume (in lots).
void Lots(
double lots
// Lots
Parameters
lots
[in] Trading volume (in lots).
3699
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
Checks the specified trading volume for correctness.
3700
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
Note
The function always returns the fixed trade volume, defined by Lots method.
3701
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for short position.
Note
The function always returns the fixed trade volume, defined by Lots method.
3702
Standard Library
CMoneyFixedMargin
CMoneyFixedMargin is the class designed to implement money management algorithm based on
trading with predefined fixed margin.
Description
CMoneyFixedMargin implements money management algorithm based on trading with predefined fixed
margin.
Declaration
class CMoneyFixedMargin: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedMargin.mqh>
Class Methods
Money and Risk Management Methods
virtual CheckOpenLong
virtual CheckOpenShort
3703
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
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.
3704
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for short position.
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.
3705
Standard Library
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
Money and Risk Management Methods
virtual CheckOpenLong
virtual CheckOpenShort
3706
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
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.
3707
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for short position.
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.
3708
Standard Library
CMoneyNone
CMoneyNone is a class with implementation of trading algorithm with minimal allowed lot.
Description
CMoneyNone class implements trading with minimal allowed lot.
Declaration
class CMoneyNone: public CExpertMoney
Title
#include <Expert\Money\MoneyNone.mqh>
Class Methods
Initialization
virtual ValidationSettings
virtual CheckOpenShort
3709
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
The function always returns true.
3710
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
Note
The function always returns the minimal lot size.
3711
Standard Library
CheckOpenShort
Gets trade volume for long position.
virtual double CheckOpenShort(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for short position.
Note
The function always returns the minimal lot size.
3712
Standard Library
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
virtual ValidationSettings
virtual CheckOpenShort
3713
Standard Library
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.
3714
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Return Value
true if successful, otherwise false.
Note
If the value of decrease factor is negative, it returns false, otherwise it returns true.
3715
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
Note
The function returns trade volume for long position, the volume dependent on results of the
previous deals.
3716
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort(
double price,
// Price
double sl
Parameters
price
[in] Price.
sl
[in] Stop Loss price.
Return Value
Trade volume for long position.
Note
The function returns trade volume for short position, the volume dependent on results of the
previous deals.
3717
Standard Library
Description
CRect
CDateTime
Base classes
Description
CWnd
CWndObj
CWndContainer
Simple controls
Description
CLabel
CBmpButton
CButton
CEdit
CPanel
CPicture
Complex controls
Description
CScroll
CScrollV
CScrollH
CWndClient
CListView
ListView
CComboBox
ComboBox
3718
Standard Library
CCheckBox
CheckBox
CCheckGroup
CheckGroup
CRadioButton
RadioButton
CRadioGroup
RadioGroup
CSpinEdit
SpinEdit
CDialog
Dialog
CAppDialog
Application Dialog
3719
Standard Library
CRect
CRect is a class of the rectangular area of the chart.
Description
CRect is a class of the area, it is defined by both coordinates of the upper-left and lower-right corners
of a rectangle in Cartesian coordinates.
Declaration
class CRect
Title
#include <Controls\Rect.mqh>
Class Methods
Properties
Left
Top
Right
Bottom
Width
Height
SetBound
Move
Shift
Contains
Additional methods
Format
3720
Standard Library
Return Value
X coordinate of the upper-left corner.
// new x coordinate
Parameters
x
[in] New X coordinate of the upper-left corner.
Return Value
None.
3721
Standard Library
Return Value
Y coordinate of the upper-left corner.
// y coordinate
Parameters
y
[in] New Y coordinate of the upper-left corner.
Return Value
None.
3722
Standard Library
Return Value
X coordinate of the lower-right corner.
// x coordinate
Parameters
x
[in] New X coordinate of the lower-right corner.
Return Value
None.
3723
Standard Library
Return Value
Y coordinate of the lower-right corner.
// y coordinate
Parameters
y
[in] New Y coordinate of the lower-right corner.
Return Value
None.
3724
Standard Library
Return Value
Width of the area.
// width
Parameters
w
[in] New width.
Return Value
true if successful, otherwise false.
3725
Standard Library
Return Value
Height of the area.
// height
Parameters
h
[in] New height.
Return Value
true if successful, otherwise false.
3726
Standard Library
SetBound
Sets new coordinates of the area using CRect class coordinates.
void SetBound(
const & CRect rect
// CRect class
Return Value
None.
SetBound
Sets new coordinates of the area.
void SetBound(
const int l
// left
const int t
// top
const int r
// right
const int b
// bottom
Parameters
l
[in] X coordinate of the upper-left corner.
t
[in] Y coordinate of the upper-left corner.
r
[in] X coordinate of the lower-right corner.
b
[in] Y coordinate of the lower-right corner.
Return Value
None.
3727
Standard Library
Move
Sets new coordinates of the CRect class.
void Move(
const int x,
// X coordinate
const int y
// Y coordinate
Parameters
x
[in] New X coordinate.
y
[in] New Y coordinate.
Return Value
None.
3728
Standard Library
Shift
Performs the relative shift of the CRect class coordinates.
void Shift(
const int dx,
// delta X
const int dy
// delta Y
Parameters
dx
[in] Delta X.
dy
[in] Delta Y.
Return Value
None.
3729
Standard Library
Contains
Checks if the point is inside the CRect class area.
bool Contains(
const int x,
// X coordinate
const int y
// Y coordinate
Parameters
x
[in] X coordinate.
y
[in] Y coordinate.
Return Value
true, if the point is inside the area (including borders), otherwise - false.
3730
Standard Library
Format
Gets the area coordinates as string.
string Format(
string & fmt,
// format
) const
Parameters
fmt
[in] String with format.
Return Value
String with the area coordinates.
3731
Standard Library
CDateTime
CDateTime is a structure for working with date and time.
Description
CDateTime is a structure derived from MqlDateTime, it used for operation with date and time in
controls.
Declaration
struct CDateTime
Title
#include <Tools\DateTime.mqh>
Class Methods
Properties
MonthName
ShortMonthName
DayName
ShortDayName
DaysInMonth
Get/Set methods
DateTime
Date
Sets date
Time
Sets time
Sec
Sets seconds
Min
Sets minutes
Hour
Sets hour
Day
Mon
Sets month
Year
Sets year
Additional methods
SecDec
SecInc
MinDec
3732
Standard Library
MinInc
HourDec
HourInc
DayDec
DayInc
MonDec
MonInc
YearDec
YearInc
3733
Standard Library
MonthName
Gets month name.
string MonthName() const
num
// month index
) const
Parameters
num
[in] Month index (1-12).
Return Value
Month name.
3734
Standard Library
ShortMonthName
Gets short month name.
string ShortMonthName() const
num
// month index
) const
Parameters
num
[in] Month index (1-12).
Return Value
Short month name.
3735
Standard Library
DayName
Gets full name of the day in a week.
string DayName() const
num
// day index
) const
Parameters
num
[in] Day index (0-6).
Return Value
Name of the day.
3736
Standard Library
ShortDayName
Gets short name of the day in a week.
string ShortDayName() const
num
// day index
) const
Parameters
num
[in] Day index (0-6).
Return Value
Short name of the day.
3737
Standard Library
DaysInMonth
Gets number of days in month.
int DaysInMonth() const
Return Value
Number of days in month.
3738
Standard Library
Return Value
Value of datetime type.
value
Parameters
value
[in] Value of datetime type.
Return Value
None.
&value
Parameters
value
[in] Value of MqlDateTime type.
Return Value
None.
3739
Standard Library
value
// date
Parameters
value
[in] Value of datetime type.
Return Value
None.
&value
// date
Parameters
value
[in] Value of MqlDateTime type.
Return Value
None.
3740
Standard Library
value
// time
Parameters
value
[in] Value of datetime type.
Return Value
None.
&value
// time
Parameters
value
[in] Value of MqlDateTime type.
Return Value
None.
3741
Standard Library
Sec
Sets seconds.
void Sec(
const int
value
// seconds
Parameters
value
[in] Seconds.
Return Value
None.
3742
Standard Library
Min
Sets minutes.
void Min(
const int
value
// minutes
Parameters
value
[in] Minutes.
Return Value
None.
3743
Standard Library
Hour
Sets hour.
void Hour(
const int
value
// hour
Parameters
value
[in] Hour.
Return Value
None.
3744
Standard Library
Day
Sets day of the month.
void Day(
const int
value
// day
Parameters
value
[in] Day of month.
Return Value
None.
3745
Standard Library
Mon
Sets month.
void Day(
const int
value
// month
Parameters
value
[in] Month.
Return Value
None.
3746
Standard Library
Year
Sets year.
void Day(
const int
value
// year
Parameters
value
[in] Year.
Return Value
None.
3747
Standard Library
SecDec
Subtracts specified number of seconds.
void SecDec(
int
delta=1
// seconds
Parameters
delta
[in] Seconds to subtract.
Return Value
None.
3748
Standard Library
SecInc
Adds specified number of seconds.
void SecInc(
int
delta=1
// seconds
Parameters
delta
[in] Seconds to add.
Return Value
None.
3749
Standard Library
MinDec
Subtracts specified number of minutes.
void MinDec(
int
delta=1
// minutes
Parameters
delta
[in] Minutes to subtract.
Return Value
None.
3750
Standard Library
MinInc
Adds specified number of minutes.
void MinInc(
int
delta=1
// minutes
Parameters
delta
[in] Minutes to add.
Return Value
None.
3751
Standard Library
HourDec
Subtracts specified number of hours.
void HourDec(
int
delta=1
// hours
Parameters
delta
[in] Hours to subtract.
Return Value
None.
3752
Standard Library
HourInc
Adds specified number of hours.
void HourInc(
int
delta=1
// hours
Parameters
delta
[in] Hours to add.
Return Value
None.
3753
Standard Library
DayDec
Subtracts specified number of days.
void DayDec(
int
delta=1
// days
Parameters
delta
[in] Days to subtract.
Return Value
None.
3754
Standard Library
DayInc
Adds specified number of days.
void DayInc(
int
delta=1
// days
Parameters
delta
[in] Days to add.
Return Value
None.
3755
Standard Library
MonDec
Subtracts specified number of months.
void MonDec(
int
delta=1
// months
Parameters
delta
[in] Months to subtract.
Return Value
None.
3756
Standard Library
MonInc
Adds specified number of months.
void MonInc(
int
delta=1
// months
Parameters
delta
[in] Months to add.
Return Value
None.
3757
Standard Library
YearDec
Subtracts specified number of years.
void YearDec(
int
delta=1
// years
Parameters
delta
[in] Years to subtract.
Return Value
None.
3758
Standard Library
YearInc
Adds specified number of years.
void YearInc(
int
delta=1
// years
Parameters
delta
[in] Years to add.
Return Value
None.
3759
Standard Library
CWnd
CWnd is a base class for all controls, included in the MQL5 Standard Library.
Description
CWnd class is the implementation of the base control class.
Declaration
class CWnd : public CObject
Title
#include <Controls\Wnd.mqh>
Class Methods
Create and destroy
Create
Creates control
Destroy
Destroys control
OnMouseEvent
Event
handler
for
CHARTEVENT_MOUSE_MOVE event
the
Name
Name
Access to container
ControlsTotal
Control
ControlFind
Geometry
Rect
Left
Top
Right
Bottom
3760
Standard Library
Width
Height
Move
Shift
Resize
Contains
Align
Alignment
Align
Identification
Id
State
IsEnabled
Enable
Disable
IsVisible
Visible
Show
Hide
IsActive
Activate
Deactivate
State flags
StateFlags
StateFlagsSet
StateFlagsReset
Properties flags
PropFlags
PropFlagsSet
PropFlagsReset
3761
Standard Library
Mouse operations
MouseX
MouseY
MouseFlags
MouseFocusKill
OnDestroy
OnMove
OnResize
OnEnable
OnDisable
OnShow
OnHide
OnActivate
OnDeactivate
OnClick
OnChange
OnMouseUp
OnDragProcess
OnDragEnd
Drag object
DragObjectCreate
DragObjectDestroy
3762
Standard Library
Create
Creates a control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper-left corner.
y1
[in] Y coordinate of the upper-left corner.
x2
[in] X coordinate of the lower-right corner.
y2
[in] Y coordinate of the lower-right corner.
Return Value
true if successful, otherwise false.
Note
Base class method only saves the parameters and always returns true.
3763
Standard Library
Destroy
Destroys a control.
virtual bool Destroy()
Return Value
true if successful, otherwise false.
3764
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
3765
Standard Library
OnMouseEvent
Mouse event handler (the CHARTEVENT_MOUSE_MOVE chart event).
virtual bool OnMouseEvent(
const int x,
// x coordinate
const int y,
// y coordinate
// flags
Parameters
x
[in] X coordinate of the mouse cursor relative to the upper-left corner of the chart.
y
[in] Y coordinate of the mouse cursor relative to the upper-left corner of the chart.
flags
[in] Flag of mouse buttons states.
Return Value
true - if the event has been processed, otherwise false.
3766
Standard Library
Name
Gets control name.
string Name() const
Return Value
Control name.
3767
Standard Library
ControlsTotal
Gets the number of controls in the container.
int ControlsTotal() const
Return Value
Number of controls in container.
Note
The base class method doesn't have the container, it provides the access to container for its heirs
and always returns 0.
3768
Standard Library
Control
Gets the control by index.
CWnd* Control(
const int ind
// index
) const
Parameters
ind
[in] Control index.
Return Value
A pointer to the control.
Note
The base class method doesn't have the container, it provides the access to container for its heirs
and always returns NULL.
3769
Standard Library
ControlFind
Gets the control from container by specified ID.
virtual CWnd* ControlFind(
const long id
// ID
Parameters
id
[in] Identifier of the control to find.
Return Value
Pointer to the control.
Note
The base class method doesn't have the container, it provides the access to container for its heirs.
If the specified ID match with the container ID, it returns a pointer to itself (this).
3770
Standard Library
Rect
Gets the pointer to the CRect class object.
const CRect* Rect() const
Return Value
Pointer to the CRect class object.
3771
Standard Library
Return Value
X coordinate of the upper-left corner of the control.
// new x coordinate
Parameters
x
[in] New X coordinate of the upper-left corner.
Return Value
None.
3772
Standard Library
Return Value
Y coordinate of the upper-left corner of the control.
// y coordinate
Parameters
y
[in] New Y coordinate of the upper-left corner.
Return Value
None.
3773
Standard Library
Return Value
X coordinate of the lower-right corner.
// x coordinate
Parameters
x
[in] New X coordinate of the lower-right corner.
Return Value
None.
3774
Standard Library
Return Value
Y coordinate of the lower-right corner of the control.
// y coordinate
Parameters
y
[in] New Y coordinate of the lower-right corner.
Return Value
None.
3775
Standard Library
Return Value
Width of the control.
// width
Parameters
w
[in] New width.
Return Value
true if successful, otherwise false.
3776
Standard Library
Return Value
Height of the control.
// height
Parameters
h
[in] New height.
Return Value
true if successful, otherwise false.
3777
Standard Library
Move
Sets new coordinates of the control.
void Move(
const int x,
// X coordinate
const int y
// Y coordinate
Parameters
x
[in] New X coordinate.
y
[in] New Y coordinate.
Return Value
None.
3778
Standard Library
Shift
Performs the relative shift of the control coordinates.
void Shift(
const int dx,
// delta X
const int dy
// delta Y
Parameters
dx
[in] Delta X.
dy
[in] Delta Y.
Return Value
None.
3779
Standard Library
Resize
Sets new width/height of the control.
virtual bool Resize(
const int w,
// width
const int h
// height
Parameters
w
[in] New width.
h
[in] New height.
Return Value
true if successful, otherwise false.
3780
Standard Library
Contains
Checks if the point is inside the control area of the chart.
bool Contains(
const int x,
// X coordinate
const int y
// Y coordinate
Parameters
x
[in] X coordinate.
y
[in] Y coordinate.
Return Value
true, if the point is inside the area (including borders), otherwise - false.
Contains
Checks if the specified control is inside the control area of the chart.
bool Contains(
const CWnd* control
// pointer
) const
Parameters
control
[in] Object pointer.
Return Value
true, if the specified control is inside the area (including borders), otherwise - false.
3781
Standard Library
Alignment
Sets alignment parameters of the control.
void Alignment(
const int flags,
// alignment flags
Parameters
flags
[in] Alignment flags.
left
[in] Fixed offset from the left border.
top
[in] Fixed offset from the top border.
right
[in] Fixed offset from the right border.
bottom
[in] Fixed offset from the bottom border.
Return Value
None.
Note
Alignement flags:
enum WND_ALIGN_FLAGS
{
WND_ALIGN_NONE=0,
// no align
WND_ALIGN_LEFT=1,
// align left
WND_ALIGN_TOP=2,
// align top
WND_ALIGN_RIGHT=4,
// align right
WND_ALIGN_BOTTOM=8,
// align bottom
// align height
3782
Standard Library
Align
Performs control alignment in the specified chart area.
virtual bool Align(
const CRect* rect
// pointer
Parameters
rect
[in] Pointer to the object with chart area coordinates.
Return Value
true if successful, otherwise false.
Note
The alignment parameters must be specified (no alignment by default).
3783
Standard Library
Id (Get Method)
Gets the control ID.
long Id() const
Return Value
The control identifier.
Id (Set Method)
Sets new value of the control ID.
virtual long Id(
const long id
// identifier
Parameters
id
[in] New value of the control identifier.
Return Value
None.
3784
Standard Library
IsEnabled
Gets a value indicating whether the control is enabled.
bool IsEnabled() const
Return Value
true - if the control is enabled, otherwise - false.
3785
Standard Library
Enable
Enables the control.
virtual bool Enable()
Return Value
true if successful, otherwise false.
Note
If the control is enabled, it's able to process the external events.
3786
Standard Library
Disable
Disables the control.
virtual bool Disable()
Return Value
true if successful, otherwise false.
Note
The disabled control isn't able to process the external events.
3787
Standard Library
IsVisible
Gets a value indicating whether the control is visible.
bool IsVisible() const
Return Value
true if the control is shown on the chart, otherwise false.
3788
Standard Library
Visible
Sets the visibility flag.
virtual bool Visible(
const bool flag
// flag
Parameters
flag
[in] New flag.
Return Value
true if successful, otherwise false.
3789
Standard Library
Show
Shows the control.
virtual bool Show()
Return Value
true if successful, otherwise false.
3790
Standard Library
Hide
Hides the control.
virtual bool Hide()
Return Value
true if successful, otherwise false.
3791
Standard Library
IsActive
Gets a value indicating whether the control is active.
bool IsActive() const
Return Value
true if the control is active, otherwise false.
3792
Standard Library
Activate
Activates the control.
virtual bool Activate()
Return Value
true if successful, otherwise false.
Note
The control becomes active when the mouse cursor is hovering over it.
3793
Standard Library
Deactivate
Deactivates the control.
virtual bool Deactivate()
Return Value
true if successful, otherwise false.
Note
The control becomes inactive when the mouse cursor is out off the control.
3794
Standard Library
Return Value
The control state flags.
// flags
Parameters
flags
[in] New control state flags.
Return Value
None.
3795
Standard Library
StateFlagsSet
Sets the control state flags.
virtual void StateFlagsSet(
const int flags
// flags
Parameters
flags
[in] Flags to set (bit mask).
Return Value
None.
3796
Standard Library
StateFlagsReset
Resets the control state flags.
virtual void StateFlagsReset(
const int flags
// flags
Parameters
flags
[in] Flags to reset (bit mask).
Return Value
None.
3797
Standard Library
// flags
Return Value
The control properties flags.
// flags
Parameters
flags
[in] New flags.
Return Value
None.
3798
Standard Library
PropFlagsSet
Sets the control properties flags.
virtual void PropFlagsSet(
const int flags
// flags
Parameters
flags
[in] Flags to set (bit mask).
Return Value
None.
3799
Standard Library
PropFlagsReset
Resets the control properties flags.
virtual void PropFlagsReset(
const int flags
// flags
Parameters
flags
[in] Flags to reset (bit mask).
Return Value
None.
3800
Standard Library
// coordinate
Parameters
value
[in] The X coordinate of the mouse.
Return Value
None.
Return Value
The saved X coordinate of the mouse.
3801
Standard Library
// coordinate
Parameters
value
[in] The Y coordinate of the mouse.
Return Value
None.
Return Value
The saved Y coordinate of the mouse.
3802
Standard Library
// state
Parameters
value
[in] State of mouse buttons.
Return Value
None.
Return Value
State of mouse buttons.
3803
Standard Library
MouseFocusKill
Clears the saved state of mouse buttons and deactivates the control.
bool MouseFocusKill(
const long id=CONTROLS_INVALID_ID
// id
Parameters
id=CONTROLS_INVALID_ID
[in] Identifier of the control, that received mouse focus.
Return Value
The control deactivation result.
3804
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3805
Standard Library
OnDestroy
The control "Destroy" event handler.
virtual bool OnDestroy()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3806
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3807
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3808
Standard Library
OnEnable
The control "Enable" (if enabled, it can respond to user interaction) event handler.
virtual bool OnEnable()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3809
Standard Library
OnDisable
The control "Disable" (if disabled it can't respond to user interaction) event handler.
virtual bool OnDisable()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3810
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3811
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3812
Standard Library
OnActivate
The control "Activate" event handler.
virtual bool OnActivate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3813
Standard Library
OnDeactivate
The control "Deactivate" event handler.
virtual bool OnDeactivate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3814
Standard Library
OnClick
The control "Click" (left mouse button click) event handler.
virtual bool OnClick()
Return Value
true if the event has been processed, otherwise false.
3815
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3816
Standard Library
OnMouseDown
The control "MouseDown" event handler.
virtual bool OnMouseDown()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseDown" event occurs when left mouse button is pressed on the control.
3817
Standard Library
OnMouseUp
The control "MouseUp" (left mouse button release) event handler.
virtual bool OnMouseUp()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseUp" event occurs when left mouse button is released on the control.
3818
Standard Library
OnDragStart
The control "DragStart" event handler.
virtual bool OnDragStart()
Return Value
true if the event has been processed, otherwise false.
Note
The "DragStart" event occurs at the start of drag operation.
3819
Standard Library
OnDragProcess
The control "DragProcess" event handler.
virtual bool OnDragProcess(
const int x,
// x coordinate
const int y
// y coordinate
Parameters
x
[in] Current X coordinate of mouse cursor.
y
[in] Current Y coordinate of mouse cursor.
Return Value
true if the event has been processed, otherwise false.
Note
The "DragProcess" event occurs when the control is moved.
3820
Standard Library
OnDragEnd
The control "DragEnd" event handler.
virtual bool OnDragEnd()
Return Value
true if the event has been processed, otherwise false.
Note
The "DragEnd" event occurs when control drag process is finished.
3821
Standard Library
DragObjectCreate
Creates drag object.
virtual bool DragObjectCreate()
Return Value
true if successful, otherwise false.
Note
true if the event has been processed, otherwise false.
3822
Standard Library
DragObjectDestroy
Destroys drag object.
virtual bool DragObjectDestroy()
Return Value
true if successful, otherwise false.
3823
Standard Library
CWndObj
CWndObj is a base class for simple controls (based on chart objects) of the Standard Library.
Description
CWndObj class implements base methods of the simple control.
Declaration
class CWndObj : public CWnd
Title
#include <Controls\WndObj.mqh>
Class Methods
Chart events processing
OnEvent
Properties
Text
Color
ColorBackground
ColorBorder
Gets/Sets
the
OBJPROP_BORDER_COLOR
property of the chart object
Font
FontSize
ZOrder
OnObjectChange
OnObjectDelete
OnObjectDrag
3824
Standard Library
OnSetColor
OnSetColorBackground
OnSetFont
OnSetFontSize
OnSetZOrder
OnChange
3825
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
3826
Standard Library
Return Value
The value of the OBJPROP_TEXT property.
// new value
Parameters
value
[in] New value of the OBJPROP_TEXT property.
Return Value
true if successful, otherwise false.
3827
Standard Library
Return Value
The value of the OBJPROP_COLOR property.
// value
Parameters
value
[in] New value of the OBJPROP_COLOR property.
Return Value
true if successful, otherwise false.
3828
Standard Library
Return Value
The value of the OBJPROP_BGCOLOR property.
// value
Parameters
value
[in] New value of the OBJPROP_BGCOLOR property.
Return Value
true if successful, otherwise false.
3829
Standard Library
Return Value
The value of the OBJPROP_BORDER_COLOR property.
// value
Parameters
value
[in] New value of the OBJPROP_BORDER_COLOR property.
Return Value
true if successful, otherwise false.
3830
Standard Library
Return Value
The value of the OBJPROP_FONT property.
// new value
Parameters
value
[in] New value of the OBJPROP_FONT property.
Return Value
true if successful, otherwise false.
3831
Standard Library
Return Value
The value of the OBJPROP_FONTSIZE property.
// new value
Parameters
value
[in] New value of the OBJPROP_FONTSIZE property.
Return Value
true if successful, otherwise false.
3832
Standard Library
Return Value
The value of the OBJPROP_ZORDER property.
// new value
Parameters
value
[in] New value of the OBJPROP_ZORDER property.
Return Value
true if successful, otherwise false.
3833
Standard Library
OnObjectCreate
The chart object CHARTEVENT_OBJECT_CREATE event handler.
virtual bool OnObjectCreate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3834
Standard Library
OnObjectChange
The chart object CHARTEVENT_OBJECT_CHANGE event handler.
virtual bool OnObjectChange()
Return Value
true if the event has been processed, otherwise false.
3835
Standard Library
OnObjectDelete
The chart object CHARTEVENT_OBJECT_DELETE event handler.
virtual bool OnObjectDelete()
Return Value
true if the event has been processed, otherwise false.
3836
Standard Library
OnObjectDrag
The chart object CHARTEVENT_OBJECT_DRAG event handler.
virtual bool OnObjectDrag()
Return Value
true if the event has been processed, otherwise false.
3837
Standard Library
OnSetText
The control "SetText" (change of the OBJPROP_TEXT property) event handler.
virtual bool OnSetText()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3838
Standard Library
OnSetColor
The control "SetColor" (change of the OBJPROP_COLOR property) event handler.
virtual bool OnSetColor()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3839
Standard Library
OnSetColorBackground
The control "SetColorBackground" (change of the OBJPROP_BGCOLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3840
Standard Library
OnSetFont
The control "SetFont" (change of the OBJPROP_FONT property) event handler.
virtual bool OnSetFont()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3841
Standard Library
OnSetFontSize
The control "SetFontSize" (change of the OBJPROP_FONTSIZE property) event handler.
virtual bool OnSetFontSize()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3842
Standard Library
OnSetZOrder
The control "SetZOrder" (change of the OBJPROP_ZORDER property) event handler.
virtual bool OnSetZOrder()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3843
Standard Library
OnDestroy
The control "Destroy" event handler.
virtual bool OnDestroy()
Return Value
true if the event has been processed, otherwise false.
3844
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
3845
Standard Library
CWndContainer
CWndContainer is a base class for a complex control (containing dependent controls) of the Standard
library.
Description
CWndContainer class implements base methods of the complex control.
Declaration
class CWndContainer : public CWnd
Title
#include <Controls\WndContainer.mqh>
Class Methods
Destroy
Destroy
OnMouseEvent
Access to container
ControlsTotal
Control
ControlFind
Gets control by ID
Add/Delete
Add
Delete
Geometry
Move
Shift
Identification
Id
State
Enable
3846
Standard Library
Disable
Show
Hide
Mouse operations
MouseFocusKill
File operations
Save
Load
OnActivate
OnDeactivate
3847
Standard Library
Destroy
Destroys all the container controls.
virtual bool Destroy()
Return Value
true if successful, otherwise false.
3848
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
3849
Standard Library
OnMouseEvent
Mouse event handler.
virtual bool OnMouseEvent(
const int x,
// x coordinate
const int y,
// y coordinate
// flags
Parameters
x
[in] X coordinate of the mouse cursor relative to the upper-left corner of the chart.
y
[in] Y coordinate of the mouse cursor relative to the upper-left corner of the chart.
flags
[in] Flag of mouse buttons states.
Return Value
true - if the event has been processed, otherwise false.
3850
Standard Library
ControlsTotal
Gets the number of controls in the container.
int ControlsTotal() const
Return Value
Number of controls in the contrainer.
3851
Standard Library
Control
Gets control from the container by index.
CWnd* Control(
const int ind
// index
) const
Parameters
ind
[in] Index of the control needed.
Return Value
Pointer to the control, otherwise NULL if the control isn't found.
3852
Standard Library
ControlFind
Gets control from the container by identifier.
virtual CWnd* ControlFind(
const long id
// id
Parameters
id
[in] Control ID.
Return Value
Pointer to the control, otherwise NULL if the control isn't found.
3853
Standard Library
Add
Adds a control to the container.
bool Add(
CWnd& control
// reference
Parameters
control
[in] Control to add, passed by reference.
Return Value
true if successful, otherwise false.
3854
Standard Library
Delete
Deletes control from the container.
bool Delete(
CWnd& control
// reference
Parameters
control
[in] Control to delete, passed by reference.
Return Value
true if successful, otherwise false.
3855
Standard Library
Move
Sets new coordinates for all controls of the container.
virtual bool Move(
const int x,
// x coordinate
const int y
// y coordinate
Parameters
x
[in] New X coordinate of the upper-left corner.
y
[in] New Y coordinate of the upper-left corner.
Return Value
true if successful, otherwise false.
3856
Standard Library
Shift
Performs the relative shift of the coordinates for all controls of the container.
virtual bool Shift(
const int dx,
// delta x
const int dy
// delta y
Parameters
dx
[in] Delta X.
dy
[in] Delta Y.
Return Value
true if successful, otherwise false.
3857
Standard Library
Id
Sets the ID for all controls of the container.
virtual long Id(
const long id
// identifier
Parameters
id
[in] Base group identifier.
Return Value
Number of identifiers, used by container controls.
3858
Standard Library
Enable
Enables all the controls of the container.
virtual bool Enable()
Return Value
true if successful, otherwise false.
3859
Standard Library
Disable
Disables all controls of the container.
virtual bool Disable()
Return Value
true if successful, otherwise false.
3860
Standard Library
Show
Shows all controls of the container.
virtual bool Show()
Return Value
true if successful, otherwise false.
3861
Standard Library
Hide
Hides all controls of the container.
virtual bool Hide()
Return Value
true if successful, otherwise false.
3862
Standard Library
MouseFocusKill
Clears the saved state of mouse buttons and deactivates all controls in the container.
bool MouseFocusKill(
const long id=CONTROLS_INVALID_ID
// id
Parameters
id=CONTROLS_INVALID_ID
[in] Identifier of the control, that received mouse focus.
Return Value
The controls deactivation result.
3863
Standard Library
Save
Saves container information to file.
virtual bool Save(
const int file_handle
// handle
Parameters
file_handle
[in] Handle of the binary file (must be opened for writing).
Return Value
true if successful, otherwise false.
3864
Standard Library
Load
Loads container information from file
virtual bool Load(
const int file_handle
// handle
Parameters
file_handle
[in] Handle of the binary file (must be opened for reading).
Return Value
true if successful, otherwise false.
3865
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3866
Standard Library
OnActivate
The control "Activate" event handler.
virtual bool OnActivate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3867
Standard Library
OnDeactivate
The control "Deactivate" event handler.
virtual bool OnDeactivate()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3868
Standard Library
CLabel
CLabel is class of the simple control, based on "Text label" chart object.
Description
CLabel is intended for creation of simple text labels.
Declaration
class CLabel : public CWndObj
Title
#include <Controls\Label.mqh>
Class Methods
Create
Create
Creates control
OnSetColor
OnSetFont
OnSetFontSize
OnShow
OnHide
OnMove
3869
Standard Library
Create
Creates new CLabel control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3870
Standard Library
OnSetText
The control "SetText" (change of the OBJPROP_TEXT property) event handler.
virtual bool OnSetText()
Return Value
true if the event has been processed, otherwise false.
3871
Standard Library
OnSetColor
The control "SetColor" (change of the OBJPROP_COLOR property) event handler.
virtual bool OnSetColor()
Return Value
true if the event has been processed, otherwise false.
3872
Standard Library
OnSetFont
The control "SetFont" (change of the OBJPROP_FONT property) event handler.
virtual bool OnSetFont()
Return Value
true if the event has been processed, otherwise false.
3873
Standard Library
OnSetFontSize
The control "SetFontSize" (change of the OBJPROP_FONTSIZE property) event handler.
virtual bool OnSetFontSize()
Return Value
true if the event has been processed, otherwise false.
3874
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3875
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3876
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3877
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3878
Standard Library
CBmpButton
CBmpButton is class of the simple control, based on "Bitmap label" chart object.
Description
CBmpButton is intended for creation of buttons with graphic image.
Declaration
class CBmpButton : public CWndObj
Title
#include <Controls\BmpButton.mqh>
Class Methods
Create
Create
Creates control
Properties
Border
BmpNames
BmpOffName
BmpOnName
BmpPassiveName
BmpActiveName
State
Pressed
Locking
OnCreate
OnShow
OnHide
OnMove
3879
Standard Library
OnChange
OnActivate
OnDeactivate
OnMouseDown
OnMouseUp
3880
Standard Library
Create
Creates new CBmpButton control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3881
Standard Library
Return Value
The "Border" property.
// new value
Parameters
value
[in] New value of the "Border" property.
Return Value
true if successful, otherwise false.
3882
Standard Library
BmpNames
Sets the name of bmp files of the control
bool BmpNames(
const string off="",
// file name
// file name
Parameters
off=""
[in] Name of bmp file for OFF state.
on=""
[in] Name of bmp file for ON state.
Return Value
true if successful, otherwise false.
3883
Standard Library
Return Value
Name of bmp file for OFF state.
// file name
Parameters
name
[in] Name of bmp file for OFF state.
Return Value
true if successful, otherwise false.
3884
Standard Library
Return Value
Name of bmp file for ON state.
// file name
Parameters
name
[in] Name of bmp file for ON state.
Return Value
true if successful, otherwise false.
3885
Standard Library
Return Value
Name of bmp file for the control passive state.
// file name
Parameters
name
[in] Name of bmp file for the control passive state.
Return Value
true if successful, otherwise false.
3886
Standard Library
Return Value
Name of bmp file for the active state.
Note
The control becomes active when the mouse cursor is hovering over it.
// file name
Parameters
name
[in] Name of bmp file for the active state.
Return Value
true if successful, otherwise false.
3887
Standard Library
Return Value
Control state.
// new state
Parameters
pressed
[in] New control state.
Return Value
true if successful, otherwise false.
3888
Standard Library
Return Value
The value of "Locking" property.
// new value
Parameters
locking
[in] New value of "Locking" property.
Return Value
None.
3889
Standard Library
OnSetZOrder
The control "SetZOrder" (change of the OBJPROP_ZORDER property) event handler.
virtual bool OnSetZOrder()
Return Value
true if the event has been processed, otherwise false.
3890
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3891
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3892
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3893
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3894
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
3895
Standard Library
OnActivate
The control "Activate" event handler.
virtual bool OnActivate()
Return Value
true if the event has been processed, otherwise false.
3896
Standard Library
OnDeactivate
The control "Deactivate" event handler.
virtual bool OnDeactivate()
Return Value
true if the event has been processed, otherwise false.
3897
Standard Library
OnMouseDown
The control "MouseDown" event handler.
virtual bool OnMouseDown()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseDown" event occurs when left mouse button is pressed on the control.
3898
Standard Library
OnMouseUp
The control "MouseUp" (left mouse button release) event handler.
virtual bool OnMouseUp()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseUp" event occurs when left mouse button is released on the control.
3899
Standard Library
CButton
CButton is class of the simple control, based on "Button" chart object.
Description
CButton class in intended for creation of simple buttons.
Declaration
class CButton : public CWndObj
Title
#include <Controls\Button.mqh>
Class Methods
Create
Create
Creates control
State
Pressed
Locking
OnSetColor
OnSetColorBackground
OnSetColorBorder
OnSetFont
OnSetFontSize
OnShow
OnHide
OnMove
OnResize
OnMouseDown
OnOnMouseUp
3900
Standard Library
3901
Standard Library
Create
Creates new CButton control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3902
Standard Library
Return Value
Control state.
// new state
Parameters
pressed
[in] New control state.
Return Value
true if successful, otherwise false.
3903
Standard Library
Return Value
The value of "Locking" property.
// new value
Parameters
locking
[in] New value of "Locking" property.
Return Value
None.
3904
Standard Library
OnSetText
The control "SetText" (change of the OBJPROP_TEXT property) event handler.
virtual bool OnSetText()
Return Value
true if the event has been processed, otherwise false.
3905
Standard Library
OnSetColor
The control "SetColor" (change of the OBJPROP_COLOR property) event handler.
virtual bool OnSetColor()
Return Value
true if the event has been processed, otherwise false.
3906
Standard Library
OnSetColorBackground
The control "SetColorBackground" (change of the OBJPROP_BGCOLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3907
Standard Library
OnSetColorBorder
The control "SetColorBorder" (change of the OBJPROP_BORDER_COLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3908
Standard Library
OnSetFont
The control "SetFont" (change of the OBJPROP_FONT property) event handler.
virtual bool OnSetFont()
Return Value
true if the event has been processed, otherwise false.
3909
Standard Library
OnSetFontSize
The control "SetFontSize" (change of the OBJPROP_FONTSIZE property) event handler.
virtual bool OnSetFontSize()
Return Value
true if the event has been processed, otherwise false.
3910
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3911
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3912
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3913
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3914
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
3915
Standard Library
OnMouseDown
The control "MouseDown" event handler.
virtual bool OnMouseDown()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseDown" event occurs when left mouse button is pressed on the control.
3916
Standard Library
OnMouseUp
The control "MouseUp" (left mouse button release) event handler.
virtual bool OnMouseUp()
Return Value
true if the event has been processed, otherwise false.
Note
The "MouseUp" event occurs when left mouse button is released on the control.
3917
Standard Library
CEdit
CEdit is class of the simple control, based on "Edit" chart object.
Description
CEdit class in intended for creation of controls, in which the user can enter text.
Declaration
class CEdit : public CWndObj
Title
#include <Controls\Edit.mqh>
Class Methods
Create
Create
Creates control
Properties
ReadOnly
TextAlign
The CHARTEVENT_OBJECT_ENDEDIT
handler (virtual)
OnSetColor
OnSetColorBackground
OnSetColorBorder
OnSetFont
OnSetFontSize
OnSetZOrder
OnShow
OnHide
OnMove
event
3918
Standard Library
OnResize
OnChange
OnClick
3919
Standard Library
Create
Creates new CEdit control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3920
Standard Library
Return Value
The value of "ReadOnly" property.
// new values
Parameters
flag
[in] New value of "ReadOnly" property.
Return Value
true if successful, otherwise false.
3921
Standard Library
Return Value
Value of "TextAlign" property of the control.
// new value
Parameters
align
[in] New value of "TextAlign" property.
Return Value
true if successful, false if property hasn't changed.
3922
Standard Library
OnObjectEndEdit
The CHARTEVENT_OBJECT_ENDEDIT event handler.
virtual bool OnObjectEndEdit()
Return Value
true if the event has been processed, otherwise false.
3923
Standard Library
OnSetText
The control "SetText" (change of the OBJPROP_TEXT property) event handler.
virtual bool OnSetText()
Return Value
true if the event has been processed, otherwise false.
3924
Standard Library
OnSetColor
The control "SetColor" (change of the OBJPROP_COLOR property) event handler.
virtual bool OnSetColor()
Return Value
true if the event has been processed, otherwise false.
3925
Standard Library
OnSetColorBackground
The control "SetColorBackground" (change of the OBJPROP_BGCOLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3926
Standard Library
OnSetColorBorder
The control "SetColorBorder" (change of the OBJPROP_BORDER_COLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3927
Standard Library
OnSetFont
The control "SetFont" (change of the OBJPROP_FONT property) event handler.
virtual bool OnSetFont()
Return Value
true if the event has been processed, otherwise false.
3928
Standard Library
OnSetFontSize
The control "SetFontSize" (change of the OBJPROP_FONTSIZE property) event handler.
virtual bool OnSetFontSize()
Return Value
true if the event has been processed, otherwise false.
3929
Standard Library
OnSetZOrder
The control "SetZOrder" (change of the OBJPROP_ZORDER property) event handler.
virtual bool OnSetZOrder()
Return Value
true if the event has been processed, otherwise false.
3930
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3931
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3932
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3933
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3934
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
3935
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
3936
Standard Library
OnClick
The control "Click" (left mouse button click) event handler.
virtual bool OnClick()
Return Value
true if the event has been processed, otherwise false.
3937
Standard Library
CPanel
CPanel is class of the simple control, based on "Rectangle label" chart object.
Description
CPanel class is intended to combine the controls with similar functions in the group.
Declaration
class CPanel : public CWndObj
Title
#include <Controls\Panel.mqh>
Class Methods
Create
Create
Creates control
OnSetColorBackground
OnSetColorBorder
OnShow
OnHide
OnMove
OnResize
OnChange
3938
Standard Library
Create
Creates new CPanel control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3939
Standard Library
Return Value
The value of "BorderType" property.
// value
Parameters
type
[in] New value of "BorderType" property.
Return Value
true if successful, otherwise false.
3940
Standard Library
OnSetText
The control "SetText" (change of the OBJPROP_TEXT property) event handler.
virtual bool OnSetText()
Return Value
true if the event has been processed, otherwise false.
3941
Standard Library
OnSetColorBackground
The control "SetColorBackground" (change of the OBJPROP_BGCOLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3942
Standard Library
OnSetColorBorder
The control "SetColorBorder" (change of the OBJPROP_BORDER_COLOR property) event handler.
virtual bool OnSetColorBackground()
Return Value
true if the event has been processed, otherwise false.
3943
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3944
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3945
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3946
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3947
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
3948
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
3949
Standard Library
CPicture
CPicture is class of the simple control, based on "Bitmap Label" chart object.
Description
CPicture class is intended for creation of simple graphic images.
Declaration
class CPicture : public CWndObj
Title
#include <Controls\Picture.mqh>
Class Methods
Create
Create
Creates control
BmpName
Internal events
OnCreate
OnShow
OnHide
OnMove
OnChange
3950
Standard Library
Create
Creates new CPicture control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3951
Standard Library
Return Value
The "Border" property.
// new value
Parameters
value
[in] New value of the "Border" property.
Return Value
true if successful, otherwise false.
3952
Standard Library
Return Value
Name of bmp file of the control.
// file name
Parameters
name
[in] Name of bmp file of the control.
Return Value
true if successful, otherwise false.
3953
Standard Library
OnCreate
The control "Create" event handler.
virtual bool OnCreate()
Return Value
true if the event has been processed, otherwise false.
3954
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3955
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3956
Standard Library
OnMove
The control "Move" event handler.
virtual bool OnMove()
Return Value
true if the event has been processed, otherwise false.
3957
Standard Library
OnChange
The control "Change" event handler.
virtual bool OnChange()
Return Value
true if the event has been processed, otherwise false.
3958
Standard Library
CScroll
CScroll is a base class for creation of scroll bars.
Description
CScroll is a complex control (with dependent controls), it contains the base functionality for creation of
scroll bars. The base class itself isn't used as a separate control, two of its heirs (CScrollV and CScrollH
classes) are used as controls.
Declaration
class CScroll : public CWndContainer
Title
#include <Controls\Scrolls.mqh>
Class Methods
Create
Create
Creates control
Properties
MinPos
MaxPos
CurrPos
CreateInc
CreateDec
CreateThumb
OnClickDec
3959
Standard Library
OnHide
OnChangePos
OnThumbDragProcess
OnThumbDragEnd
Position
CalcPos
3960
Standard Library
Create
Creates new CScroll control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
3961
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
3962
Standard Library
Return Value
New value of "MinPos" property.
// new value
Parameters
value
[in] New value of "MinPos" property.
Return Value
None.
3963
Standard Library
Return Value
New value of "MaxPos" property.
// new value
Parameters
value
[in] New value of "MaxPos" property.
Return Value
None.
3964
Standard Library
Return Value
New value of "CurrPos" property.
// new value
Parameters
value
[in] New value of "CurrPos" property.
Return Value
None.
3965
Standard Library
CreateBack
Creates background button of the CScroll control.
virtual bool CreateBack()
Return Value
true if successful, otherwise false.
3966
Standard Library
CreateInc
Creates increment button of the CScroll control.
virtual bool CreateInc()
Return Value
true if successful, otherwise false.
3967
Standard Library
CreateDec
Creates decrement button of CScroll control.
virtual bool CreateDec()
Return Value
true if successful, otherwise false.
3968
Standard Library
CreateThumb
Creates thumb button (can be dragged) of the CScroll control.
virtual bool CreateThumb()
Return Value
true if successful, otherwise false.
3969
Standard Library
OnClickInc
The control "ClickInc" (left mouse button click on the increment button) event handler.
virtual bool OnClickInc()
Return Value
true if the event has been processed, otherwise false.
3970
Standard Library
OnClickDec
The control "ClickDec" (left mouse button click on the decrement button) event handler.
virtual bool OnClickDec()
Return Value
true if the event has been processed, otherwise false.
3971
Standard Library
OnShow
The control "Show" event handler.
virtual bool OnShow()
Return Value
true if the event has been processed, otherwise false.
3972
Standard Library
OnHide
The control "Hide" event handler.
virtual bool OnHide()
Return Value
true if the event has been processed, otherwise false.
3973
Standard Library
OnChangePos
The control "ChangePos" (position change) event handler.
virtual bool OnChangePos()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
3974
Standard Library
OnThumbDragStart
The control "ThumbDragStart" (drag start) event handler.
virtual bool OnThumbDragStart()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragStart" event occurs at start of the drag operation.
3975
Standard Library
OnThumbDragProcess
The control "ThumbDragProcess" event handler.
virtual bool OnThumbDragProcess(
const int x,
// x coordinate
const int y
// y coordinate
Parameters
x
[in] Current X coordinate of mouse cursor.
y
[in] Current Y coordinate of mouse cursor.
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragProcess" occurs when the scroll bar control (thumb button) is moved.
3976
Standard Library
OnThumbDragEnd
The control "ThumbDragEnd" (drag process finished) event handler.
virtual bool OnThumbDragEnd()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragEnd" occurs when the drag operation of the scroll bar control (thumb button) is
finished.
3977
Standard Library
CalcPos
Gets scroll bar position by coordinate.
virtual int CalcPos(
const int
coord
// coordinate
Parameters
coord
[in] Scroll bar coordinate.
Return Value
Scroll bar position.
3978
Standard Library
CScrollV
CScrollV is a class of the "Vertical scroll bar" complex control.
Description
CScrollV class is intended for creation of vertical scroll bars.
Declaration
class CScrollV : public CScroll
Title
#include <Controls\Scrolls.mqh>
Class Methods
Dependent controls
CreateInc
CreateDec
CreateThumb
OnChangePos
OnThumbDragProcess
OnThumbDragEnd
Position
CalcPos
3979
Standard Library
CreateInc
Creates increment button of the control.
virtual bool CreateInc()
Return Value
true if successful, otherwise false.
3980
Standard Library
CreateDec
Creates decrement button of the control.
virtual bool CreateDec()
Return Value
true if successful, otherwise false.
3981
Standard Library
CreateThumb
Creates thumb button (can be dragged) of the control.
virtual bool CreateThumb()
Return Value
true if successful, otherwise false.
3982
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
3983
Standard Library
OnChangePos
The control "ChangePos" (position change) event handler.
virtual bool OnChangePos()
Return Value
true if the event has been processed, otherwise false.
3984
Standard Library
OnThumbDragStart
The control "ThumbDragStart" (drag start) event handler.
virtual bool OnThumbDragStart()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragStart" event occurs at start of the drag operation.
3985
Standard Library
OnThumbDragProcess
The control "ThumbDragProcess" event handler.
virtual bool OnThumbDragProcess(
const int x,
// x coordinate
const int y
// y coordinate
Parameters
x
[in] Current X coordinate of mouse cursor.
y
[in] Current Y coordinate of mouse cursor.
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragProcess" occurs when the scroll bar control (thumb button) is moved.
3986
Standard Library
OnThumbDragEnd
The control "ThumbDragEnd" (drag process finished) event handler.
virtual bool OnThumbDragEnd()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragEnd" occurs when the drag operation of the scroll bar control (thumb button) is
finished.
3987
Standard Library
CalcPos
Gets scroll bar position by coordinate.
virtual int CalcPos(
const int
coord
// coordinate
Parameters
coord
[in] Scroll bar coordinate.
Return Value
Scroll bar position.
3988
Standard Library
CScrollH
CScrollH is a class of the "Horizontal scroll bar" complex control.
Description
CScrollH is intended for creation of horizontal scroll bars.
Declaration
class CScrollH : public CScroll
Title
#include <Controls\Scrolls.mqh>
Class Methods
Dependent controls
CreateInc
CreateDec
CreateThumb
OnChangePos
OnThumbDragProcess
OnThumbDragEnd
Position
CalcPos
3989
Standard Library
CreateInc
Creates increment button of the control.
virtual bool CreateInc()
Return Value
true if successful, otherwise false.
3990
Standard Library
CreateDec
Creates decrement button of the control.
virtual bool CreateDec()
Return Value
true if successful, otherwise false.
3991
Standard Library
CreateThumb
Creates thumb button (can be dragged) of the control.
virtual bool CreateThumb()
Return Value
true if successful, otherwise false.
3992
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
3993
Standard Library
OnChangePos
The control "ChangePos" (position change) event handler.
virtual bool OnChangePos()
Return Value
true if the event has been processed, otherwise false.
3994
Standard Library
OnThumbDragStart
The control "ThumbDragStart" (drag start) event handler.
virtual bool OnThumbDragStart()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragStart" event occurs at start of the drag operation.
3995
Standard Library
OnThumbDragProcess
The control "ThumbDragProcess" event handler.
virtual bool OnThumbDragProcess(
const int x,
// x coordinate
const int y
// y coordinate
Parameters
x
[in] Current X coordinate of mouse cursor.
y
[in] Current Y coordinate of mouse cursor.
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragProcess" occurs when the scroll bar control (thumb button) is moved.
3996
Standard Library
OnThumbDragEnd
The control "ThumbDragEnd" (drag process finished) event handler.
virtual bool OnThumbDragEnd()
Return Value
true if the event has been processed, otherwise false.
Note
The "ThumbDragEnd" occurs when the drag operation of the scroll bar control (thumb button) is
finished.
3997
Standard Library
CalcPos
Gets scroll bar position by coordinate.
virtual int CalcPos(
const int
coord
// coordinate
Parameters
coord
[in] Scroll bar coordinate.
Return Value
Scroll bar position.
3998
Standard Library
CWndClient
CWndClient is a class of the "Cient area" complex control (with dependent controls). It's a base class
for creation of scroll bars area.
Description
CWndClient implements the functionality for creation of client area with scroll bars.
Declaration
class CWndClient : public CWndContainer
Title
#include <Controls\WndClient.mqh>
Class Methods
Create
Create
Creates control
Properties
ColorBackground
ColorBorder
BorderType
Settings
VScrolled
HScrolled
Dependent controls
CreateBack
CreateScrollV
CreateScrollH
of
VScroll
3999
Standard Library
OnVScrollHide
of
VScroll
OnHScrollShow
of
HScroll
OnHScrollHide
of
HScroll
OnScrollLineDown
OnScrollLineUp
OnScrollLineLeft
OnScrollLineRight
of
Resize
Rebound
4000
Standard Library
Create
Creates new CWndClient control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4001
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4002
Standard Library
ColorBackground
Sets background color of the control.
bool ColorBackground(
const color value
// new color
Parameters
value
[in] New background color of the control.
Return Value
true if successful, otherwise false.
4003
Standard Library
ColorBorder
Set border color of the control.
bool ColorBorder(
const color value
// color
Parameters
value
[in] New border color of the control.
Return Value
true if successful, otherwise false.
4004
Standard Library
BorderType
Sets border type of the control.
bool BorderType(
const ENUM_BORDER_TYPE type
// border type
Parameters
type
[in] Border type of the control.
Return Value
true if successful, otherwise false.
4005
Standard Library
Return Value
true, if vertical scroll bar is used, otherwise false.
// flag
Parameters
flag
[in] Flag.
Return Value
true if successful, otherwise false.
4006
Standard Library
Return Value
true, if horizontal scroll bar is used, otherwise false.
// flag
Parameters
flag
[in] Flag.
Return Value
true if successful, otherwise false.
4007
Standard Library
CreateBack
Creates background button of the control.
virtual bool CreateBack()
Return Value
true if successful, otherwise false.
4008
Standard Library
CreateScrollV
Creates vertical scroll bar.
virtual bool CreateScrollV()
Return Value
true if successful, otherwise false.
4009
Standard Library
CreateScrollH
Creates horizontal scroll bar.
virtual bool CreateScrollH()
Return Value
true if successful, otherwise false.
4010
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
4011
Standard Library
OnVScrollShow
The control "VScrollShow" (vertical scroll bar show) event handler.
virtual bool OnVScrollShow()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4012
Standard Library
OnVScrollHide
The control "VScrollHide" (vertical scroll bar hide) event handler.
virtual bool OnVScrollHide()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4013
Standard Library
OnHScrollShow
The control "HScrollShow" (horizontal scroll bar show) event handler.
virtual bool OnHScrollShow()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4014
Standard Library
OnHScrollHide
The control "HScrollHide" (horizontal scroll bar hide) event handler.
virtual bool OnHScrollHide()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4015
Standard Library
OnScrollLineDown
The control "ScrollLineDown" (vertical scroll line down) event handler.
virtual bool OnScrollLineDown()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4016
Standard Library
OnScrollLineUp
The control "ScrollLineUp" (vertical scroll line up) event handler.
virtual bool OnScrollLineUp()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4017
Standard Library
OnScrollLineLeft
The control "ScrollLineLeft" (horizontal scroll line left) event handler.
virtual bool OnScrollLineLeft()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4018
Standard Library
OnScrollLineRight
The control "ScrollLineRight" (horizontal scroll line right) event handler.
virtual bool OnScrollLineRight()
Return Value
true if the event has been processed, otherwise false.
Note
The base class method does nothing and always returns true.
4019
Standard Library
ReBound
Sets new coordinates of the control using CRect class coordinates.
void ReBound(
const & CRect rect
// CRect class
Return Value
None.
4020
Standard Library
CListView
CListView is a class of the ListView complex control (with dependent controls).
Description
CListView class encapsulates list-control functionality.
Declaration
class CListView : public CWndClient
Title
#include <Controls\ListView.mqh>
Class Methods
Create
Create
Creates control
Settings
TotalView
Add/Delete
AddItem
Adds an item
Data
Select
SelectByText
SelectByValue
Read-only data
Value
Dependent controls
CreateRow
of
VScroll
4021
Standard Library
OnVScrollHide
of
VScroll
OnScrollLineDown
OnScrollLineUp
OnItemClick
Redraw
Redraw
RowState
CheckView
4022
Standard Library
Create
Creates new CListView control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4023
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4024
Standard Library
TotalView
Sets the number of items, shown on the control.
bool TotalView(
const int value
// items shown
Parameters
value
[in] The number of items, shown on the control.
Return Value
true if successful, otherwise false.
Note
The number of shown items can be specified only at once.
4025
Standard Library
AddItem
Adds an item to the control.
bool AddItem(
const string item,
// text
const long
// value
value
Parameters
item
[in] Text.
value
[in] Value of long type.
Return Value
true if successful, otherwise false.
4026
Standard Library
Select
Selects current list element by index.
bool Select(
const int index
// index
Parameters
index
[in] Item index.
Return Value
true if successful, otherwise false.
4027
Standard Library
SelectByText
Selects current list element by text.
bool SelectByText(
const string text
// text
Parameters
text
[in] Text.
Return Value
true if successful, otherwise false.
4028
Standard Library
SelectByValue
Selects current list element by value.
bool SelectByValue(
const long value
// value
Parameters
value
[in] Value of long type.
Return Value
true if successful, otherwise false.
4029
Standard Library
Value
Gets the value of current list element.
long Value()
Return Value
The value of current list element.
4030
Standard Library
CreateRow
Creates a row of the CListView control.
bool CreateRow(
const int index
// index
Parameters
index
[in] Item index.
Return Value
true if successful, otherwise false.
4031
Standard Library
OnResize
The control "Resize" event handler.
virtual bool OnResize()
Return Value
true if the event has been processed, otherwise false.
4032
Standard Library
OnVScrollShow
The control "VScrollShow" (vertical scroll bar show) event handler.
virtual bool OnVScrollShow()
Return Value
true if the event has been processed, otherwise false.
4033
Standard Library
OnVScrollHide
The control "VScrollHide" (vertical scroll bar hide) event handler.
virtual bool OnVScrollHide()
Return Value
true if the event has been processed, otherwise false.
4034
Standard Library
OnScrollLineDown
The control "ScrollLineDown" (vertical scroll line down) event handler.
virtual bool OnScrollLineDown()
Return Value
true if the event has been processed, otherwise false.
4035
Standard Library
OnScrollLineUp
The control "ScrollLineUp" (vertical scroll line up) event handler.
virtual bool OnScrollLineUp()
Return Value
true if the event has been processed, otherwise false.
4036
Standard Library
OnItemClick
The control "ItemClick" (mouse button click on a row) event handler.
virtual bool OnItemClick()
const int
index
// row index
Return Value
true if the event has been processed, otherwise false.
4037
Standard Library
Redraw
Redraws the control.
bool Redraw()
Return Value
true if successful, otherwise false.
4038
Standard Library
RowState
Sets the state of the specified row.
bool RowState(
const int
index
// index
// state
Parameters
index
[in] Row index.
select
[in] Row state.
Return Value
true if successful, otherwise false.
4039
Standard Library
CheckView
Checks the "visibility" of the specified row.
bool CheckView()
Return Value
true, if the selected row is visible, othewise false.
4040
Standard Library
CComboBox
CComboBox is a class of the ComboBox complex control (with dependent controls).
Description
ComboBox consists of a list box, combined with a static control, intended for selection. The list-box
portion of the control may be drop down when the user selects the drop-down arrow next to the control
Declaration
class CComboBox : public CWndContainer
Title
#include <Controls\ComboBox.mqh>
Class Methods
Create
Create
Creates control
Add
AddItem
Adds an item
Settings
ListViewItems
Data
Select
SelectByText
SelectByValue
Read-only data
Value
Dependent controls
CreateEdit
CreateButton
CreateList
4041
Standard Library
OnClickButton
OnChangeList
Show/Hide
ListShow
ListHide
4042
Standard Library
Create
Creates new CComboBox control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4043
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4044
Standard Library
AddItem
Adds an item to the control.
bool AddItem(
const string item,
// text
const long
// value
value
Parameters
item
[in] Text.
value=0
[in] Value of long type.
Return Value
true if successful, otherwise false.
4045
Standard Library
ListViewItems
Sets the number of list elements of the CComboBox control.
void ListViewItems(
const int
value
Parameters
value
[in] Number of list elements.
Return Value
true if successful, otherwise false.
4046
Standard Library
Select
Selects current list element by index.
bool Select(
const int index
// index
Parameters
index
[in] Item index.
Return Value
true if successful, otherwise false.
4047
Standard Library
SelectByText
Selects current list element by text.
bool SelectByText(
const string text
// text
Parameters
text
[in] Text of the item.
Return Value
true if successful, otherwise false.
4048
Standard Library
SelectByValue
Selects current list element by value.
bool SelectByValue(
const long value
// value
Parameters
value
[in] Value of long type.
Return Value
true if successful, otherwise false.
4049
Standard Library
Value
Gets the value of the current list element.
long Value()
Return Value
The value of the current list element.
4050
Standard Library
CreateEdit
Creates dependent control (edit) of the control.
virtual bool CreateEdit()
Return Value
true if successful, otherwise false.
4051
Standard Library
CreateButton
Creates dependent control (button).
virtual bool CreateButton()
Return Value
true if successful, otherwise false.
4052
Standard Library
CreateList
Creates dependent control (list view).
virtual bool CreateList()
Return Value
true if successful, otherwise false.
4053
Standard Library
OnClickEdit
The control "ClickEdit" (mouse click on the edit) event handler.
virtual bool OnClickEdit()
Return Value
true if the event has been processed, otherwise false.
4054
Standard Library
OnClickButton
The control "ClickButton" (mouse click on the button) event handler.
virtual bool OnClickButton()
Return Value
true if the event has been processed, otherwise false.
4055
Standard Library
OnChangeList
The "ChangeList" (change of the list) event handler.
virtual bool OnChangeList()
Return Value
true if the event has been processed, otherwise false.
4056
Standard Library
ListShow
Shows the items list.
virtual bool ListShow()
Return Value
true if successful, otherwise false.
4057
Standard Library
ListHide
Hides the items list.
virtual bool ListHide()
Return Value
true if successful, otherwise false.
4058
Standard Library
CCheckBox
CCheckBox is class of the CheckBox complex control.
Description
CCheckBox control displays a check box that allows the user to select a true or false condition.
Declaration
class CCheckBox : public CWndContainer
Title
#include <Controls\CheckBox.mqh>
Class Methods
Create
Create
Creates control
Properties
Text
Color
State
Checked
Data
Value
Dependent controls
CreateButton
CreateLabel
ClickLabel
4059
Standard Library
Create
Creates new CCheckBox control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4060
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4061
Standard Library
Return Value
Text of the label.
// text
Parameters
value
[in] New text of the label.
Return Value
true if successful, otherwise false.
4062
Standard Library
Return Value
Label color.
// color
Parameters
value
[in] New label color.
Return Value
true if successful, otherwise false.
4063
Standard Library
Return Value
State of the control.
// state
Parameters
flag
[in] New state.
Return Value
true if successful, otherwise false.
4064
Standard Library
Return Value
The value, associated with the control.
// new value
Parameters
value
[in] New value.
Return Value
None.
4065
Standard Library
CreateButton
Creates dependent control (button).
virtual bool CreateButton()
Return Value
true if successful, otherwise false.
4066
Standard Library
CreateLabel
Creates dependent control (label).
virtual bool CreateLabel()
Return Value
true if successful, otherwise false.
4067
Standard Library
OnClickButton
The control "ClickButton" (mouse click on the button) event handler.
virtual bool OnClickButton()
Return Value
true if the event has been processed, otherwise false.
4068
Standard Library
OnClickLabel
The control "ClickLabel" (mouse click on the label) event handler.
virtual bool OnClickLabel()
Return Value
true if the event has been processed, otherwise false.
4069
Standard Library
CCheckGroup
CCheckGroup is a class of the CheckGroup complex control (with dependent controls).
Description
CCheckGroup provides the possibility for creation of controls, which allow to display and edit flags.
Declaration
class CCheckGroup : public CWndClient
Title
#include <Controls\CheckGroup.mqh>
Class Methods
Create
Create
Creates control
Add
AddItem
Read-only data
Value
Dependent controls
CreateButton
of
VScroll
OnVScrollHide
of
VScroll
OnScrollLineDown
OnScrollLineUp
OnChangeItem
Redraw
Redraw
4070
Standard Library
RowState
4071
Standard Library
Create
Creates new CCheckGroup control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4072
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4073
Standard Library
AddItem
Adds an item to the control.
bool AddItem(
const string item,
// text
const long
// value
value
Parameters
item
[in] Text.
value=0
[in] Value of long type.
Return Value
true if successful, otherwise false.
4074
Standard Library
Value
Gets the value, associated with the control.
long Value()
Return Value
The value, associated with the control.
Note
The value depends on state of all items of the CCheckGroup.
4075
Standard Library
CreateButton
Creates new CCheckBox class instance on the specified index.
bool CreateButton(
int index
// index
Parameters
index
[in] Index of the new item in the CCheckGroup.
Return Value
true if successful, otherwise false.
4076
Standard Library
OnVScrollShow
The control "VScrollShow" (vertical scroll bar show) event handler.
virtual bool OnVScrollShow()
Return Value
true if the event has been processed, otherwise false.
4077
Standard Library
OnVScrollHide
The control "VScrollHide" (vertical scroll bar hide) event handler.
virtual bool OnVScrollHide()
Return Value
true if the event has been processed, otherwise false.
4078
Standard Library
OnScrollLineDown
The control "ScrollLineDown" (vertical scroll line down) event handler.
virtual bool OnScrollLineDown()
Return Value
true if the event has been processed, otherwise false.
4079
Standard Library
OnScrollLineUp
The control "ScrollLineUp" (vertical scroll line up) event handler.
virtual bool OnScrollLineUp()
Return Value
true if the event has been processed, otherwise false.
4080
Standard Library
OnChangeItem
The control "ChangeItem" (item change) event handler.
virtual bool OnChangeItem(
const int index
// index
Parameters
index
[in] Index of the changed item.
Return Value
true if the event has been processed, otherwise false.
4081
Standard Library
Redraw
Redraws the control.
bool Redraw()
Return Value
true if successful, otherwise false.
4082
Standard Library
RowState
Sets the state of the specified item.
bool RowState(
const int
index,
// item index
// state
Parameters
index
[in] Item index to change.
select
[in] New state.
Return Value
true if successful, otherwise false.
4083
Standard Library
CRadioButton
CRadioButton is a class of RadioButton complex control.
Description
CRadioButton itself is not used, it used for creation of CRadioGroup items.
Declaration
class CRadioButton : public CWndContainer
Title
#include <Controls\RadioButton.mqh>
Class Methods
Create
Create
Creates control
Properties
Text
Color
State
State
Dependent controls
CreateButton
Creates button
CreateLabel
Creates label
OnClickLabel
4084
Standard Library
Create
Creates new CRadioButton control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4085
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4086
Standard Library
Return Value
Text of the label.
// text
Parameters
value
[in] New text of the label.
Return Value
true if successful, otherwise false.
4087
Standard Library
Return Value
Label color.
// color
Parameters
value
[in] New label color.
Return Value
true if successful, otherwise false.
4088
Standard Library
Return Value
Button state.
// flag
Parameters
flag
[in] New button state.
Return Value
true if successful, otherwise false.
4089
Standard Library
CreateButton
Creates button.
virtual bool CreateButton()
Return Value
true if successful, otherwise false.
4090
Standard Library
CreateLabel
Creates label.
virtual bool CreateLabel()
Return Value
true if successful, otherwise false.
4091
Standard Library
OnClickButton
The control "ClickButton" (mouse click) event handler.
virtual bool OnClickButton()
Return Value
true if the event has been processed, otherwise false.
4092
Standard Library
OnClickLabel
The control "ClickLabel" (mouse click on the label) event handler.
virtual bool OnClickLabel()
Return Value
true if the event has been processed, otherwise false.
4093
Standard Library
CRadioGroup
CRadioGroup is class of the RadioGroup complex control (with dependent controls).
Description
CRadioGroup enables the user to select a single option from a group of choices when paired with other
CRadioButton controls.
Declaration
class CRadioGroup : public CWndClient
Title
#include <Controls\RadioGroup.mqh>
Class Methods
Create
Create
Creates control
Add
AddItem
Read-only data
Value
Dependent controls
CreateButton
of
VScroll
OnVScrollHide
of
VScroll
OnScrollLineDown
OnScrollLineUp
OnChangeItem
Redraw
Redraw
4094
Standard Library
RowState
Select
4095
Standard Library
Create
Creates new CRadioGroup control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4096
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4097
Standard Library
AddItem
Adds an item to the control.
bool AddItem(
const string item,
// text
const long
// value
value=0
Parameters
item
[in] Text.
value=0
[in] Value of long type.
Return Value
true if successful, otherwise false.
4098
Standard Library
Value
Gets the value, associated with the control.
long Value()
Return Value
The value, associated with the control.
Note
The value depends on state of all CRadioButton items of the CRadioGroup control.
4099
Standard Library
CreateButton
Creates new CRadioButton class instance on the specified index.
bool CreateButton(
const int index
// index
Parameters
index
[in] Index of the new item in the CRadioGroup.
Return Value
true if successful, otherwise false.
4100
Standard Library
OnVScrollShow
The control "VScrollShow" (vertical scroll bar show) event handler.
virtual bool OnVScrollShow()
Return Value
true if the event has been processed, otherwise false.
4101
Standard Library
OnVScrollHide
The control "VScrollHide" (vertical scroll bar hide) event handler.
virtual bool OnVScrollHide()
Return Value
true if the event has been processed, otherwise false.
4102
Standard Library
OnScrollLineDown
The control "ScrollLineDown" (vertical scroll line down) event handler.
virtual bool OnScrollLineDown()
Return Value
true if the event has been processed, otherwise false.
4103
Standard Library
OnScrollLineUp
The control "ScrollLineUp" (vertical scroll line up) event handler.
virtual bool OnScrollLineUp()
Return Value
true if the event has been processed, otherwise false.
4104
Standard Library
OnChangeItem
The control "ChangeItem" (item change) event handler.
virtual bool OnChangeItem(
const int index
// index
Parameters
index
[in] Index of the changed item.
Return Value
true if the event has been processed, otherwise false.
4105
Standard Library
Redraw
Redraws the control.
bool Redraw()
Return Value
true if successful, otherwise false.
4106
Standard Library
RowState
Sets the state of the specified item.
bool RowState(
const int
index,
// item index
// state
Parameters
index
[in] Item index to change.
select
[in] New state.
Return Value
true if successful, otherwise false.
4107
Standard Library
Select
Selects current item.
void Select(
const int index
// index
Parameters
index
[in] Item index to select.
Return Value
None.
4108
Standard Library
CSpinEdit
CSpinEdit is a class of SpinEdit complex control (with dependent controls).
Description
CSpinEdit class is intended for creation of controls, which allows to edit the values of integer type. It
automatically increases data when pressing the upper button, but decreases if pressing the lower
button.
Declaration
class CSpinEdit : public CWndContainer
Title
#include <Controls\SpinEdit.mqh>
Class Methods
Create
Create
Creates control
Properties
MinValue
MaxValue
State
Value
Dependent controls
CreateEdit
CreateInc
CreateDec
OnClickDec
4109
Standard Library
Create
Creates new CSpinEdit control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4110
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4111
Standard Library
Return Value
The value of "MinValue" property.
// new value
Parameters
value
[in] New value of "MinValue" property.
Return Value
None.
4112
Standard Library
Return Value
The value of "MaxValue" property.
// new value
Parameters
value
[in] New value of "MaxValue" property.
Return Value
None.
4113
Standard Library
Return Value
The "Value" property.
// value
Parameters
value
[in] New "Value" property.
Return Value
None.
4114
Standard Library
CreateEdit
Creates dependent control (CEdit).
virtual bool CreateEdit()
Return Value
true if successful, otherwise false.
4115
Standard Library
CreateInc
Creates dependent control (increment button).
virtual bool CreateInc()
Return Value
true if successful, otherwise false.
4116
Standard Library
CreateDec
Creates dependent control (decrement button).
virtual bool CreateDec()
Return Value
true if successful, otherwise false.
4117
Standard Library
OnClickInc
The control "ClickInc" (mouse click on the increment button) event handler.
virtual bool OnClickInc()
Return Value
true if the event has been processed, otherwise false.
4118
Standard Library
OnClickDec
The control "ClickDec" (mouse click on the decrement button) event handler.
virtual bool OnClickDec()
Return Value
true if the event has been processed, otherwise false.
4119
Standard Library
OnChangeValue
The control "ChangeValue" event handler.
virtual bool OnChangeValue()
Return Value
true if the event has been processed, otherwise false.
4120
Standard Library
CDialog
CDialog is class of the Dialog complex control.
Description
CDialog class is intended to combine the controls with different functions in the group.
Declaration
class CDialog : public CWndContainer
Title
#include <Controls\Dialog.mqh>
Class Methods
Create
Create
Creates control
Properties
Caption
Add
Add
Dependent controls
CreateWhiteBorder
CreateBackground
CreateCaption
CreateButtonClose
CreateClientArea
OnClickButtonClose
ClientAreaLeft
4121
Standard Library
ClientAreaTop
ClientAreaRight
ClientAreaBottom
ClientAreaWidth
ClientAreaHeight
OnDialogDragProcess
OnDialogDragEnd
4122
Standard Library
Create
Creates new CDialog control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4123
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4124
Standard Library
Return Value
The "Caption" property.
// text
Parameters
text
[in] New value of "Caption" property.
Return Value
true if successful, otherwise false.
4125
Standard Library
Add
Adds control to the client area by pointer.
bool Add(
CWnd *control,
// pointer
Parameters
control
[in] Pointer to control.
Return Value
true if successful, otherwise false.
Add
Adds control to the client area by reference.
bool Add(
CWnd &control,
// reference
Parameters
control
[in] Reference to control.
Return Value
true if successful, otherwise false.
4126
Standard Library
CreateWhiteBorder
Creates dependent control (white border).
virtual bool CreateWhiteBorder()
Return Value
true if successful, otherwise false.
4127
Standard Library
CreateBackground
Creates dependent control (background).
virtual bool CreateBackground()
Return Value
true if successful, otherwise false.
4128
Standard Library
CreateCaption
Creates dependent control (caption).
virtual bool CreateCaption()
Return Value
true if successful, otherwise false.
4129
Standard Library
CreateButtonClose
Creates dependent control (close button)
virtual bool CreateButtonClose()
Return Value
true if successful, otherwise false.
4130
Standard Library
CreateClientArea
Creates dependent control (client area).
virtual bool CreateClientArea()
Return Value
true if successful, otherwise false.
4131
Standard Library
OnClickCaption
The control "ClickCaption" event handler.
virtual bool OnClickCaption()
Return Value
true if successful, otherwise false.
4132
Standard Library
OnClickButtonClose
The control "ClickButtonClose" event handler.
virtual bool OnClickButtonClose()
Return Value
true if successful, otherwise false.
4133
Standard Library
ClientAreaVisible
Sets a flag indicating whether the client area is visible.
bool ClientAreaVisible(
const bool visible
// visibility flag
Parameters
visible
[in] Visibility flag.
Return Value
true if successful, otherwise false.
4134
Standard Library
ClientAreaLeft
Gets X coordinate of the upper-left corner of the control client area.
int ClientAreaLeft()
Return Value
The X coordinate of the upper-left corner of the control client area.
4135
Standard Library
ClientAreaTop
Gets Y coordinate of the upper-left corner of the control client area.
int ClientAreaTop()
Return Value
The Y coordinate of the upper-left corner of the control client area.
4136
Standard Library
ClientAreaRight
Gets X coordinate of the lower-right corner of the control client area.
int ClientAreaTop()
Return Value
The X coordinate of the lower-right corner of the control client area.
4137
Standard Library
ClientAreaBottom
Gets Y coordinate of the lower-right corner of the control client area.
int ClientAreaBottom()
Return Value
The Y coordinate of the lower-right corner of the control client area.
4138
Standard Library
ClientAreaWidth
Gets the width of the control client area.
int ClientAreaWidth()
Return Value
The width of the client area.
4139
Standard Library
ClientAreaHeight
Gets the height of the control client area.
int ClientAreaHeight()
Return Value
The height of the control client area.
4140
Standard Library
OnDialogDragStart
The control "DialogDragStart" event handler.
virtual bool OnDialogDragStart()
Return Value
true if the event has been processed, otherwise false.
Note
The "DialogDragStart" event occurs at start of the drag of the control.
4141
Standard Library
OnDialogDragProcess
The control "DialogDragProcess" event handler.
virtual bool OnDialogDragProcess()
Return Value
true if the event has been processed, otherwise false.
Note
The "DialogDragProcess" event occurs when the control is dragged.
4142
Standard Library
OnDialogDragEnd
The control "DialogDragEnd" event handler.
virtual bool OnDialogDragEnd()
Return Value
true if the event has been processed, otherwise false.
Note
The "DialogDragEnd" event occurs at the end of the drag of the control.
4143
Standard Library
CAppDialog
CAppDialog is a class of Application Dialog complex control (with dependent controls).
Description
CAppDialog class is intended to combine the controls with different functions in the group inside the
MQL5 program.
Declaration
class CAppDialog : public CDialog
Title
#include <Controls\Dialog.mqh>
Class Methods
Create and destroy
Create
Creates control
Destroy
Destroys control
Events processing
OnEvent
Run
Run
Runs control
Settings
Minimized
Save/Load
IniFileSave
IniFileLoad
IniFileName
IniFileExt
Initialization
CreateCommon
4144
Standard Library
CreateExpert
CreateIndicator
Dependent controls
CreateButtonMinMax
Creates
dependent
maximize buttons)
controls
(minimize/
OnClickButtonMinMax
External events
OnAnotherApplicationClose
Methods
Rebound
Minimize
Maximize
CreateInstanceId
ProgramName
SubwinOff
4145
Standard Library
Create
Creates new CAppDialog control.
virtual bool Create(
const long
chart,
// chart ID
// name
const int
subwin,
// chart subwindow
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4146
Standard Library
Destroy
Destroys control.
virtual bool Destroy()
Return Value
true if successful, otherwise false.
4147
Standard Library
OnEvent
Chart event handler.
virtual bool OnEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4148
Standard Library
Run
Runs control.
bool Run()
Return Value
true if successful, otherwise false.
4149
Standard Library
ChartEvent
Chart event handler.
virtual bool ChartEvent(
const int
id,
// ID
const long&
lparam,
Parameters
id
[in] Event ID.
lparam
[in] Event parameter of long type, passed by reference.
dparam
[in] Event parameter of double type, passed by reference.
sparam
[in] Event parameter of string type, passed by reference.
Return Value
true - if the event has been processed, otherwise false.
4150
Standard Library
Minimized
Sets the value of "Minimized" property of the control.
bool Minimized(
const bool flag
// state
Parameters
flag
[in] New state.
Return Value
true if successful, otherwise false.
4151
Standard Library
IniFileSave
Saves the control state to file.
void IniFileSave()
Return Value
true if successful, otherwise false.
4152
Standard Library
IniFileLoad
Loads the control state from file.
void IniFileLoad()
Return Value
true if successful, otherwise false.
4153
Standard Library
IniFileName
Sets the file name for loading/saving the control state.
virtual string IniFileName()
const
Return Value
File name for loading/saving of the control state.
Note
The file name includes the name of the Expert Advisor/indicator and working symbol, on which
MQL5 program is launched.
4154
Standard Library
IniFileExt
Sets the file extension for loading/saving the control state.
virtual string IniFileExt()
const
Return Value
File extension, used for loading/saving of the control state.
4155
Standard Library
CreateCommon
Common initialization method.
bool CreateCommon(
const long
chart,
// chart ID
// name
const int
// chart subwindow
subwin,
Parameters
chart
[in] chart ID.
name
[in] Unique name of the control.
subwin
[in] Chart subwindow.
Return Value
true if successful, otherwise false.
4156
Standard Library
CreateExpert
Initialization method for working in Expert Advisors.
bool CreateExpert(
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4157
Standard Library
CreateIndicator
Initialization method for working in indicators.
bool CreateIndicator(
const int
x1,
// x1 coordinate
const int
y1,
// y1 coordinate
const int
x2,
// x2 coordinate
const int
y2
// y2 coordinate
Parameters
x1
[in] X coordinate of the upper left corner.
y1
[in] Y coordinate of the upper left corner.
x2
[in] X coordinate of the lower right corner.
y2
[in] Y coordinate of the lower right corner.
Return Value
true if successful, otherwise false.
4158
Standard Library
CreateButtonMinMax
Creates dependent controls (minimize/maximize buttons).
virtual void CreateButtonMinMax()
Return Value
None.
4159
Standard Library
OnClickButtonClose
The control "ClickButtonClose" (mouse click on close button) event handler.
virtual void OnClickButtonClose()
Return Value
None.
4160
Standard Library
OnClickButtonMinMax
The control "ClickButtonMinMax" (mouse click on minimize/maximize button) event handler.
virtual void OnClickButtonClose()
Return Value
None.
4161
Standard Library
OnAnotherApplicationClose
Event handler of external events.
virtual void OnAnotherApplicationClose()
Return Value
None.
4162
Standard Library
Rebound
Sets new coordinates of the control using CRect class coordinates.
bool Rebound(
const & CRect rect
// CRect class
Return Value
true if successful, otherwise false.
4163
Standard Library
Minimize
Shows the control in the minimized state.
virtual void Minimize()
Return Value
true if successful, otherwise false.
4164
Standard Library
Maximize
Shows the control in the maximized (restored) state.
virtual void Maximize()
Return Value
true if successful, otherwise false.
4165
Standard Library
CreateInstanceId
Creates a unique Id for the names of the control objects.
string CreateInstanceId()
Return Value
Prefix for the object names.
4166
Standard Library
ProgramName
Gets the name of the MQL5 program.
string ProgramName()
Return Value
Name of the MQL5 program.
4167
Standard Library
SubwinOff
Gets the Y offset of the control subwindow.
void SubwinOff()
Return Value
None.
4168
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.
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()
{
//--- Call function upon initialization
init();
4169
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:
mql5-program
main function
script
OnStart
indicator
OnCalculate
Expert Advisor
OnTick
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.
4170
Expert Advisors
Expert Advisors in MQL5 do not require the obligatory presence of functions that handle the events of
a new tick receipt - OnTick, as it was in MQL4 (the start function in MQL4 is executed when a new tick
is received). In MQL5 Expert Advisors can contain pre-defined handler functions of several types of
events:
OnTick receipt of a new tick;
OnTimer timer event;
OnTrade - trade event;
OnChartEvent events of input from the keyboard and mouse, events of a graphic object moving,
event of a text editing completion in the entry field of the LabelEdit object;
OnBookEvent event of Depth of Market status change.
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 MQL5 has been significantly increased. 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 the Arrow, Text and Label objects now you can specify binding methods, and for the Label, Button,
Chart, Bitmap Label and Edit objects you can set chart corner to which an object is attached.
4171
Action
Section
AccountInfoDouble
Account Information
AccountInfoInteger
Account Information
AccountInfoString
Account Information
acos
Math Functions
Alert
Displays a message
separate window
Common Functions
ArrayBsearch
Array Functions
ArrayCompare
Returns
the
result
of
comparing two arrays of
simple types
or custom
structures without complex
objects
Array Functions
ArrayCopy
Array Functions
ArrayFill
Fills an array
specified value
the
Array Functions
ArrayFree
Array Functions
ArrayGetAsSeries
Checks direction
indexing
array
Array Functions
ArrayInitialize
Array Functions
ArrayIsDynamic
Array Functions
ArrayIsSeries
Array Functions
ArrayMaximum
Searches
Array Functions
for
in
with
of
the
largest
4172
Array Functions
ArrayRange
Returns
the
number
of
elements in the specified
dimension of the array
Array Functions
ArrayResize
Array Functions
ArraySetAsSeries
Array Functions
ArraySize
Returns
the
number
elements in the array
of
Array Functions
ArraySort
Array Functions
asin
Math Functions
atan
Math Functions
Bars
BarsCalculated
Returns
the
number
of
calculated data in an indicator
buffer or -1 in the case of
error (data
hasn't been
calculated yet)
ceil
Math Functions
CharArrayToString
Conversion Functions
ChartApplyTemplate
Chart Operations
ChartClose
Chart Operations
ChartFirst
Chart Operations
ChartGetDouble
Returns
Chart Operations
the
double
value
4173
Chart Operations
ChartGetString
Chart Operations
ChartID
Chart Operations
ChartIndicatorAdd
Chart Operations
ChartIndicatorDelete
Chart Operations
ChartIndicatorGet
Chart Operations
ChartIndicatorName
Chart Operations
ChartIndicatorsTotal
Chart Operations
ChartNavigate
Chart Operations
ChartNext
Chart Operations
ChartOpen
Chart Operations
CharToString
Conversion Functions
ChartPeriod
Chart Operations
ChartPriceOnDropped
Chart Operations
ChartRedraw
Chart Operations
4174
ChartSaveTemplate
Chart Operations
ChartScreenShot
Chart Operations
ChartSetDouble
Chart Operations
ChartSetInteger
Sets
the
integer
value
(datetime, int, color, bool or
char) for a corresponding
property of the specified chart
Chart Operations
ChartSetString
Chart Operations
ChartSetSymbolPeriod
Chart Operations
ChartSymbol
Chart Operations
ChartTimeOnDropped
Chart Operations
ChartTimePriceToXY
Chart Operations
ChartWindowFind
Chart Operations
ChartWindowOnDropped
Chart Operations
ChartXOnDropped
Chart Operations
ChartXYToTimePrice
Chart Operations
4175
ChartYOnDropped
Chart Operations
CheckPointer
Common Functions
CLBufferCreate
CLBufferFree
CLBufferRead
CLBufferWrite
Writes an array
OpenCL buffer
CLContextCreate
CLContextFree
CLExecute
CLGetDeviceInfo
CLGetInfoInteger
an
an
CLHandleType
CLKernelCreate
Creates an
function
OpenCL
start
CLKernelFree
Removes
function
OpenCL
start
CLProgramCreate
CLProgramFree
CLSetKernelArg
CLSetKernelArgMem
ColorToARGB
Conversion Functions
ColorToString
Conversion Functions
an
into
an
4176
string as "R,G,B"
Comment
Common Functions
CopyBuffer
CopyClose
CopyHigh
CopyLow
CopyOpen
CopyRates
CopyRealVolume
CopySpread
CopyTicks
CopyTickVolume
CopyTime
cos
Returns
Math Functions
the
cosine
of
4177
number
CryptDecode
Performs
the
inverse
transformation of the data
from array
Common Functions
CryptEncode
Common Functions
DebugBreak
Program
debugging
Common Functions
Digits
Checkup
DoubleToString
Conversion Functions
EnumToString
Converting an enumeration
value of any type to string
Conversion Functions
EventChartCustom
EventKillTimer
EventSetMillisecondTimer
EventSetTimer
Starts
the
timer
event
generator with the specified
periodicity for the current
chart
exp
Math Functions
ExpertRemove
Common Functions
fabs
Returns
absolute
value
(modulus) of the specified
numeric value
Math Functions
FileClose
File Functions
FileCopy
File Functions
breakpoint
in
and
4178
FileDelete
File Functions
FileFindClose
File Functions
FileFindFirst
File Functions
FileFindNext
File Functions
FileFlush
File Functions
FileGetInteger
File Functions
FileIsEnding
File Functions
FileIsExist
File Functions
FileIsLineEnding
File Functions
FileMove
File Functions
FileOpen
File Functions
FileReadArray
File Functions
FileReadBool
File Functions
FileReadDatetime
File Functions
FileReadDouble
File Functions
FileReadFloat
File Functions
4179
FileReadInteger
File Functions
FileReadLong
File Functions
FileReadNumber
File Functions
FileReadString
the
file
File Functions
FileReadStruct
File Functions
FileSeek
File Functions
FileSize
File Functions
FileTell
File Functions
FileWrite
File Functions
FileWriteArray
File Functions
FileWriteDouble
File Functions
FileWriteFloat
File Functions
FileWriteInteger
File Functions
4180
FileWriteLong
File Functions
FileWriteString
File Functions
FileWriteStruct
File Functions
floor
Math Functions
fmax
Math Functions
fmin
Math Functions
fmod
Math Functions
FolderClean
the
File Functions
FolderCreate
File Functions
FolderDelete
File Functions
FrameAdd
FrameFilter
FrameFirst
FrameInputs
FrameNext
GetLastError
Checkup
in
4181
GetPointer
Common Functions
GetTickCount
Returns
the
number
of
milliseconds that have elapsed
since the system was started
Common Functions
GlobalVariableCheck
GlobalVariableDel
GlobalVariableGet
GlobalVariableName
GlobalVariablesDeleteAll
GlobalVariableSet
GlobalVariableSetOnCondition
GlobalVariablesFlush
GlobalVariablesTotal
GlobalVariableTemp
GlobalVariableTime
HistoryDealGetDouble
Returns
the
requested
property of a deal in the
history (double)
Trade Functions
HistoryDealGetInteger
Returns
the
requested
property of a deal in the
history (datetime or int)
Trade Functions
HistoryDealGetString
Returns
the
requested
property of a deal in the
history (string)
Trade Functions
4182
HistoryDealGetTicket
Returns a ticket of
a
corresponding deal in the
history
Trade Functions
HistoryDealSelect
Trade Functions
HistoryDealsTotal
Trade Functions
HistoryOrderGetDouble
Returns
the
requested
property of an order in the
history (double)
Trade Functions
HistoryOrderGetInteger
Returns
the
requested
property of an order in the
history (datetime or int)
Trade Functions
HistoryOrderGetString
Returns
the
requested
property of an order in the
history (string)
Trade Functions
HistoryOrderGetTicket
Trade Functions
HistoryOrderSelect
Trade Functions
HistoryOrdersTotal
Trade Functions
HistorySelect
Trade Functions
HistorySelectByPosition
Trade Functions
iAC
Accelerator Oscillator
Technical Indicators
iAD
Accumulation/Distribution
Technical Indicators
iADX
Technical Indicators
iADXWilder
Technical Indicators
iAlligator
Alligator
Technical Indicators
iAMA
Technical Indicators
iAO
Awesome Oscillator
Technical Indicators
iATR
Technical Indicators
4183
iBands
Bollinger Bands
Technical Indicators
iBearsPower
Bears Power
Technical Indicators
iBullsPower
Bulls Power
Technical Indicators
iBWMFI
Technical Indicators
iCCI
Technical Indicators
iChaikin
Chaikin Oscillator
Technical Indicators
iCustom
Custom indicator
Technical Indicators
iDEMA
Double Exponential
Average
iDeMarker
DeMarker
Technical Indicators
iEnvelopes
Envelopes
Technical Indicators
iForce
Force Index
Technical Indicators
iFractals
Fractals
Technical Indicators
iFrAMA
Fractal
Average
iGator
Gator Oscillator
Technical Indicators
iIchimoku
Technical Indicators
iMA
Moving Average
Technical Indicators
iMACD
Moving
Averages
Convergence-Divergence
Technical Indicators
iMFI
Technical Indicators
iMomentum
Momentum
Technical Indicators
IndicatorCreate
IndicatorParameters
IndicatorRelease
IndicatorSetDouble
Custom Indicators
Adaptive
Moving
Moving
Technical Indicators
Technical Indicators
4184
IndicatorSetInteger
Custom Indicators
IndicatorSetString
Custom Indicators
IntegerToString
Conversion Functions
iOBV
On Balance Volume
Technical Indicators
iOsMA
Technical Indicators
iRSI
Technical Indicators
iRVI
Technical Indicators
iSAR
Technical Indicators
IsStopped
Checkup
iStdDev
Standard Deviation
Technical Indicators
iStochastic
Stochastic Oscillator
Technical Indicators
iTEMA
Triple Exponential
Average
Moving
Technical Indicators
iTriX
Triple Exponential
Averages Oscillator
Moving
Technical Indicators
iVIDyA
Variable
Average
Dynamic
Technical Indicators
iVolumes
Volumes
Technical Indicators
iWPR
Technical Indicators
log
Math Functions
log10
Math Functions
MarketBookAdd
Market Info
MarketBookGet
Market Info
MarketBookRelease
Market Info
Index
4185
Returns
absolute
value
(modulus) of the specified
numeric value
Math Functions
MathArccos
Math Functions
MathArcsin
Math Functions
MathArctan
Math Functions
MathCeil
Math Functions
MathCos
Returns
number
Math Functions
MathExp
Math Functions
MathFloor
Math Functions
MathIsValidNumber
Math Functions
MathLog
Math Functions
MathLog10
Math Functions
MathMax
Math Functions
MathMin
Math Functions
MathMod
Math Functions
MathPow
the
Math Functions
MathRand
Math Functions
MathRound
Math Functions
MathSin
Math Functions
MathSqrt
Math Functions
the
cosine
of
to
4186
MathSrand
Math Functions
MathTan
Math Functions
MessageBox
Common Functions
MQLInfoInteger
Checkup
MQLInfoString
Checkup
NormalizeDouble
Conversion Functions
ObjectCreate
Object Functions
ObjectDelete
Object Functions
ObjectFind
Object Functions
ObjectGetDouble
Object Functions
ObjectGetInteger
Object Functions
ObjectGetString
Object Functions
ObjectGetTimeByValue
Object Functions
ObjectGetValueByTime
Object Functions
ObjectMove
Object Functions
ObjectName
Object Functions
of
4187
chart subwindow)
ObjectsDeleteAll
Object Functions
ObjectSetDouble
Object Functions
ObjectSetInteger
Object Functions
ObjectSetString
Object Functions
ObjectsTotal
Object Functions
OrderCalcMargin
Trade Functions
OrderCalcProfit
Trade Functions
OrderCheck
Trade Functions
OrderGetDouble
Returns
the
requested
property of the order (double)
Trade Functions
OrderGetInteger
Returns
the
requested
property
of
the
order
(datetime or int)
Trade Functions
OrderGetString
Returns
the
requested
property of the order (string)
Trade Functions
OrderGetTicket
Trade Functions
OrderSelect
Trade Functions
OrderSend
Trade Functions
OrderSendAsync
Trade Functions
of
4188
OrdersTotal
Trade Functions
ParameterGetRange
ParameterSetRange
Period
Returns the
timeframe
Checkup
PeriodSeconds
Common Functions
PlaySound
Common Functions
PlotIndexGetInteger
Custom Indicators
PlotIndexSetDouble
Custom Indicators
PlotIndexSetInteger
Custom Indicators
PlotIndexSetString
Custom Indicators
Point
Checkup
PositionGetDouble
Returns
the
requested
property of an open position
(double)
Trade Functions
PositionGetInteger
Returns
the
requested
property of an open position
(datetime or int)
Trade Functions
PositionGetString
Returns
the
requested
property of an open position
(string)
Trade Functions
PositionGetSymbol
Returns
the
corresponding to
position
symbol
the open
Trade Functions
PositionSelect
Trade Functions
current
chart
4189
Trade Functions
pow
Math Functions
Common Functions
PrintFormat
Common Functions
rand
Math Functions
ResetLastError
Sets
the
value
predetermined
_LastError to zero
of
a
variable
Common Functions
ResourceCreate
Common Functions
ResourceFree
Common Functions
ResourceReadImage
Common Functions
ResourceSave
Common Functions
round
Math Functions
SendFTP
Common Functions
SendMail
Common Functions
SendNotification
Common Functions
SeriesInfoInteger
to
the
4190
SetIndexBuffer
Custom Indicators
ShortArrayToString
Conversion Functions
ShortToString
Converting
symbol
code
(unicode) into one-symbol
string
Conversion Functions
SignalBaseGetDouble
Trade Signals
SignalBaseGetInteger
Trade Signals
SignalBaseGetString
Trade Signals
SignalBaseSelect
Trade Signals
SignalBaseTotal
Trade Signals
SignalInfoGetDouble
Trade Signals
SignalInfoGetInteger
Trade Signals
SignalInfoGetString
Trade Signals
SignalInfoSetDouble
Trade Signals
SignalInfoSetInteger
Trade Signals
SignalSubscribe
Subscribes
signal
Trade Signals
SignalUnsubscribe
Cancels subscription
Trade Signals
sin
Math Functions
to
the
trading
4191
Sleep
Common Functions
sqrt
Math Functions
srand
Math Functions
StringAdd
String Functions
StringBufferLen
String Functions
StringCompare
String Functions
StringConcatenate
String Functions
StringFill
String Functions
StringFind
String Functions
StringFormat
Conversion Functions
StringGetCharacter
String Functions
StringInit
String Functions
StringLen
String Functions
StringReplace
Replaces
all the
found
substrings of a string by a set
sequence of symbols
String Functions
StringSetCharacter
String Functions
StringSplit
String Functions
4192
String Functions
StringToCharArray
Conversion Functions
StringToColor
Conversion Functions
StringToDouble
Conversion Functions
StringToInteger
Conversion Functions
StringToLower
String Functions
StringToShortArray
Conversion Functions
StringToTime
Conversion Functions
StringToUpper
String Functions
StringTrimLeft
String Functions
StringTrimRight
String Functions
StructToTime
Converts
a
variable
of
MqlDateTime structure type
into a datetime value
Symbol
Checkup
4193
SymbolInfoDouble
Market Info
SymbolInfoInteger
Market Info
SymbolInfoMarginRate
Market Info
SymbolInfoSessionQuote
Market Info
SymbolInfoSessionTrade
Market Info
SymbolInfoString
Market Info
SymbolInfoTick
Market Info
SymbolIsSynchronized
Market Info
SymbolName
Market Info
SymbolSelect
Market Info
SymbolsTotal
Returns
the
number
of
available (selected in Market
Watch or all) symbols
Market Info
tan
Math Functions
TerminalClose
Common Functions
TerminalInfoDouble
Checkup
of
of
4194
Checkup
TerminalInfoString
Checkup
TesterStatistics
Common Functions
TextGetSize
Object Functions
TextOut
Object Functions
TextSetFont
Object Functions
TimeCurrent
TimeDaylightSavings
TimeGMT
TimeGMTOffset
TimeLocal
TimeToString
Conversion Functions
4195
TimeToStruct
TimeTradeServer
UninitializeReason
Checkup
WebRequest
Common Functions
ZeroMemory
Common Functions
4196
Description
Usage
__DATE__
__DATETIME__
__FILE__
Name
of
compiled file
currently
__FUNCSIG__
__FUNCTION__
__LINE__
__MQLBUILD__,
__MQL5BUILD__
__PATH__
ACCOUNT_ASSETS
The current
account
an
AccountInfoDouble
ACCOUNT_BALANCE
AccountInfoDouble
ACCOUNT_COMMISSION_BLOC
KED
The
current
blocked
commission amount on an
account
AccountInfoDouble
ACCOUNT_COMPANY
Name of a company
serves the account
AccountInfoString
ACCOUNT_CREDIT
AccountInfoDouble
ACCOUNT_CURRENCY
Account currency
AccountInfoString
ACCOUNT_EQUITY
AccountInfoDouble
the
assets
of
that
4197
ACCOUNT_LEVERAGE
Account leverage
AccountInfoInteger
ACCOUNT_LIABILITIES
AccountInfoDouble
ACCOUNT_LIMIT_ORDERS
AccountInfoInteger
ACCOUNT_LOGIN
Account number
AccountInfoInteger
ACCOUNT_MARGIN
AccountInfoDouble
ACCOUNT_MARGIN_FREE
AccountInfoDouble
ACCOUNT_MARGIN_INITIAL
AccountInfoDouble
ACCOUNT_MARGIN_LEVEL
Account
percents
AccountInfoDouble
ACCOUNT_MARGIN_MAINTENA
NCE
Maintenance
margin.
The
minimum equity reserved on an
account to cover the minimum
amount of all open positions
AccountInfoDouble
ACCOUNT_MARGIN_SO_CALL
AccountInfoDouble
ACCOUNT_MARGIN_SO_MODE
AccountInfoInteger
ACCOUNT_MARGIN_SO_SO
Margin
stop
out
level.
Depending
on
the
set
ACCOUNT_MARGIN_SO_MODE
is expressed in percents or in
the deposit currency
AccountInfoDouble
ACCOUNT_NAME
Client name
AccountInfoString
ACCOUNT_PROFIT
AccountInfoDouble
ACCOUNT_SERVER
AccountInfoString
ACCOUNT_STOPOUT_MODE_M
ONEY
AccountInfoInteger
ACCOUNT_STOPOUT_MODE_PE
RCENT
AccountInfoInteger
ACCOUNT_TRADE_ALLOWED
AccountInfoInteger
margin
level
in
4198
account
ACCOUNT_TRADE_EXPERT
AccountInfoInteger
ACCOUNT_TRADE_MODE
AccountInfoInteger
ACCOUNT_TRADE_MODE_CON
TEST
Contest account
AccountInfoInteger
ACCOUNT_TRADE_MODE_DEM
O
Demo account
AccountInfoInteger
ACCOUNT_TRADE_MODE_REAL
Real account
AccountInfoInteger
ALIGN_CENTER
ObjectSetInteger,
ObjectGetInteger,
ChartScreenShot
ALIGN_LEFT
Left alignment
ObjectSetInteger,
ObjectGetInteger,
ChartScreenShot
ALIGN_RIGHT
Right alignment
ObjectSetInteger,
ObjectGetInteger,
ChartScreenShot
ANCHOR_CENTER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_LEFT
ObjectSetInteger,
ObjectGetInteger
ANCHOR_LEFT_LOWER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_LEFT_UPPER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_LOWER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_RIGHT
ObjectSetInteger,
ObjectGetInteger
ANCHOR_RIGHT_LOWER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_RIGHT_UPPER
ObjectSetInteger,
ObjectGetInteger
ANCHOR_UPPER
ObjectSetInteger,
ObjectGetInteger
BASE_LINE
Main line
Indicators Lines
BOOK_TYPE_BUY
MqlBookInfo
BOOK_TYPE_BUY_MARKET
MqlBookInfo
4199
BOOK_TYPE_SELL
MqlBookInfo
BOOK_TYPE_SELL_MARKET
MqlBookInfo
BORDER_FLAT
Flat form
ObjectSetInteger,
ObjectGetInteger
BORDER_RAISED
Prominent form
ObjectSetInteger,
ObjectGetInteger
BORDER_SUNKEN
Concave form
ObjectSetInteger,
ObjectGetInteger
CHAR_MAX
CHAR_MIN
CHART_AUTOSCROLL
ChartSetInteger,
ChartGetInteger
CHART_BARS
ChartSetInteger
CHART_BEGIN
ChartNavigate
CHART_BRING_TO_TOP
ChartSetInteger,
ChartGetInteger
CHART_CANDLES
Display
as
candlesticks
ChartSetInteger
CHART_COLOR_ASK
ChartSetInteger,
ChartGetInteger
CHART_COLOR_BACKGROUND
ChartSetInteger,
ChartGetInteger
CHART_COLOR_BID
ChartSetInteger,
ChartGetInteger
CHART_COLOR_CANDLE_BEAR
Body
color
candlestick
bear
ChartSetInteger,
ChartGetInteger
CHART_COLOR_CANDLE_BULL
ChartSetInteger,
ChartGetInteger
CHART_COLOR_CHART_DOWN
ChartSetInteger,
ChartGetInteger
CHART_COLOR_CHART_LINE
ChartSetInteger,
ChartGetInteger
CHART_COLOR_CHART_UP
ChartSetInteger,
ChartGetInteger
Japanese
of
4200
CHART_COLOR_FOREGROUND
and
CHART_COLOR_GRID
Grid color
ChartSetInteger,
ChartGetInteger
CHART_COLOR_LAST
ChartSetInteger,
ChartGetInteger
CHART_COLOR_STOP_LEVEL
ChartSetInteger,
ChartGetInteger
CHART_COLOR_VOLUME
ChartSetInteger,
ChartGetInteger
CHART_COMMENT
ChartSetString,
ChartGetString
CHART_CURRENT_POS
Current position
ChartNavigate
CHART_DRAG_TRADE_LEVELS
ChartSetInteger,
ChartGetInteger
CHART_EVENT_MOUSE_MOVE
ChartSetInteger,
ChartGetInteger
CHART_EVENT_OBJECT_CREA
TE
ChartSetInteger,
ChartGetInteger
CHART_EVENT_OBJECT_DELET
E
ChartSetInteger,
ChartGetInteger
CHART_FIRST_VISIBLE_BAR
ChartSetInteger,
ChartGetInteger
CHART_FIXED_MAX
ChartSetDouble,
ChartGetDouble
CHART_FIXED_MIN
ChartSetDouble,
ChartGetDouble
CHART_FIXED_POSITION
ChartSetDouble,
ChartGetDouble
ChartSetInteger,
ChartGetInteger
4201
ChartSetInteger,
ChartGetInteger
CHART_HEIGHT_IN_PIXELS
ChartSetInteger,
ChartGetInteger
CHART_IS_OBJECT
Identifying
"Chart" (OBJ_CHART) object
returns true for a graphical
object. Returns false for a real
chart
ChartSetInteger,
ChartGetInteger
CHART_LINE
ChartSetInteger
CHART_MODE
ChartSetInteger,
ChartGetInteger
CHART_MOUSE_SCROLL
ChartSetInteger,
ChartGetInteger
CHART_POINTS_PER_BAR
ChartSetDouble,
ChartGetDouble
CHART_PRICE_MAX
Chart maximum
ChartSetDouble,
ChartGetDouble
CHART_PRICE_MIN
Chart minimum
ChartSetDouble,
ChartGetDouble
CHART_SCALE
Scale
ChartSetInteger,
ChartGetInteger
CHART_SCALE_PT_PER_BAR
ChartSetInteger,
ChartGetInteger
CHART_SCALEFIX
ChartSetInteger,
ChartGetInteger
4202
CHART_SCALEFIX_11
ChartSetInteger,
ChartGetInteger
CHART_SHIFT
ChartSetInteger,
ChartGetInteger
CHART_SHIFT_SIZE
ChartSetDouble,
ChartGetDouble
CHART_SHOW_ASK_LINE
ChartSetInteger,
ChartGetInteger
CHART_SHOW_BID_LINE
ChartSetInteger,
ChartGetInteger
CHART_SHOW_DATE_SCALE
ChartSetInteger,
ChartGetInteger
CHART_SHOW_GRID
ChartSetInteger,
ChartGetInteger
CHART_SHOW_LAST_LINE
CHART_SHOW_OBJECT_DESCR
Pop-up
descriptions
graphical objects
CHART_SHOW_OHLC
ChartSetInteger,
ChartGetInteger
of
ChartSetInteger,
ChartGetInteger
in the
ChartSetInteger,
ChartGetInteger
CHART_SHOW_ONE_CLICK
Showing
the "One
click
trading" panel on a chart
ChartSetInteger,
ChartGetInteger
CHART_SHOW_PERIOD_SEP
ChartSetInteger,
ChartGetInteger
CHART_SHOW_PRICE_SCALE
ChartSetInteger,
ChartGetInteger
CHART_SHOW_TRADE_LEVELS
ChartSetInteger,
ChartGetInteger
CHART_SHOW_VOLUMES
ChartSetInteger,
ChartGetInteger
CHART_VISIBLE_BARS
ChartSetInteger,
ChartGetInteger
CHART_VOLUME_HIDE
ChartSetInteger
CHART_VOLUME_REAL
Trade volumes
ChartSetInteger
CHART_VOLUME_TICK
Tick volumes
ChartSetInteger
CHART_WIDTH_IN_BARS
ChartSetInteger,
ChartGetInteger
4203
CHART_WIDTH_IN_PIXELS
ChartSetInteger,
ChartGetInteger
CHART_WINDOW_HANDLE
ChartSetInteger,
ChartGetInteger
CHART_WINDOW_IS_VISIBLE
Visibility of subwindows
ChartSetInteger,
ChartGetInteger
CHART_WINDOW_YDISTANCE
ChartSetInteger,
ChartGetInteger
CHART_WINDOWS_TOTAL
ChartSetInteger,
ChartGetInteger
CHARTEVENT_CHART_CHANGE
OnChartEvent
CHARTEVENT_CLICK
Clicking on a chart
OnChartEvent
CHARTEVENT_CUSTOM
OnChartEvent
CHARTEVENT_CUSTOM_LAST
OnChartEvent
CHARTEVENT_KEYDOWN
Keystrokes
OnChartEvent
CHARTEVENT_MOUSE_MOVE
OnChartEvent
4204
CHART_EVENT_MOUSE_MOVE=
true is set for the chart)
CHARTEVENT_OBJECT_CHANG
E
Graphical object
property
changed via the properties
dialog
OnChartEvent
CHARTEVENT_OBJECT_CLICK
OnChartEvent
CHARTEVENT_OBJECT_CREAT
E
OnChartEvent
CHARTEVENT_OBJECT_DELETE
OnChartEvent
CHARTEVENT_OBJECT_DRAG
OnChartEvent
CHARTEVENT_OBJECT_ENDEDI
T
OnChartEvent
CHARTS_MAX
The
maximum
possible
number of simultaneously open
charts in the terminal
Other Constants
CHIKOUSPAN_LINE
Indicators Lines
clrAliceBlue
Alice Blue
Web Colors
clrAntiqueWhite
Antique White
Web Colors
clrAqua
Aqua
Web Colors
clrAquamarine
Aquamarine
Web Colors
clrBeige
Beige
Web Colors
clrBisque
Bisque
Web Colors
clrBlack
Black
Web Colors
clrBlanchedAlmond
Blanched Almond
Web Colors
clrBlue
Blue
Web Colors
clrBlueViolet
Blue Violet
Web Colors
clrBrown
Brown
Web Colors
clrBurlyWood
Burly Wood
Web Colors
clrCadetBlue
Cadet Blue
Web Colors
clrChartreuse
Chartreuse
Web Colors
clrChocolate
Chocolate
Web Colors
clrCoral
Coral
Web Colors
4205
clrCornflowerBlue
Cornflower Blue
Web Colors
clrCornsilk
Cornsilk
Web Colors
clrCrimson
Crimson
Web Colors
clrDarkBlue
Dark Blue
Web Colors
clrDarkGoldenrod
Dark Goldenrod
Web Colors
clrDarkGray
Dark Gray
Web Colors
clrDarkGreen
Dark Green
Web Colors
clrDarkKhaki
Dark Khaki
Web Colors
clrDarkOliveGreen
Web Colors
clrDarkOrange
Dark Orange
Web Colors
clrDarkOrchid
Dark Orchid
Web Colors
clrDarkSalmon
Dark Salmon
Web Colors
clrDarkSeaGreen
Web Colors
clrDarkSlateBlue
Web Colors
clrDarkSlateGray
Web Colors
clrDarkTurquoise
Dark Turquoise
Web Colors
clrDarkViolet
Dark Violet
Web Colors
clrDeepPink
Deep Pink
Web Colors
clrDeepSkyBlue
Web Colors
clrDimGray
Dim Gray
Web Colors
clrDodgerBlue
Dodger Blue
Web Colors
clrFireBrick
Fire Brick
Web Colors
clrForestGreen
Forest Green
Web Colors
clrGainsboro
Gainsboro
Web Colors
clrGold
Gold
Web Colors
clrGoldenrod
Goldenrod
Web Colors
clrGray
Gray
Web Colors
clrGreen
Green
Web Colors
clrGreenYellow
Green Yellow
Web Colors
clrHoneydew
Honeydew
Web Colors
clrHotPink
Hot Pink
Web Colors
clrIndianRed
Indian Red
Web Colors
4206
clrIndigo
Indigo
Web Colors
clrIvory
Ivory
Web Colors
clrKhaki
Khaki
Web Colors
clrLavender
Lavender
Web Colors
clrLavenderBlush
Lavender Blush
Web Colors
clrLawnGreen
Lawn Green
Web Colors
clrLemonChiffon
Lemon Chiffon
Web Colors
clrLightBlue
Light Blue
Web Colors
clrLightCoral
Light Coral
Web Colors
clrLightCyan
Light Cyan
Web Colors
clrLightGoldenrod
Light Goldenrod
Web Colors
clrLightGray
Light Gray
Web Colors
clrLightGreen
Light Green
Web Colors
clrLightPink
Light Pink
Web Colors
clrLightSalmon
Light Salmon
Web Colors
clrLightSeaGreen
Web Colors
clrLightSkyBlue
Web Colors
clrLightSlateGray
Web Colors
clrLightSteelBlue
Web Colors
clrLightYellow
Light Yellow
Web Colors
clrLime
Lime
Web Colors
clrLimeGreen
Lime Green
Web Colors
clrLinen
Linen
Web Colors
clrMagenta
Magenta
Web Colors
clrMaroon
Maroon
Web Colors
clrMediumAquamarine
Medium Aquamarine
Web Colors
clrMediumBlue
Medium Blue
Web Colors
clrMediumOrchid
Medium Orchid
Web Colors
clrMediumPurple
Medium Purple
Web Colors
clrMediumSeaGreen
Web Colors
clrMediumSlateBlue
Web Colors
clrMediumSpringGreen
Web Colors
4207
clrMediumTurquoise
Medium Turquoise
Web Colors
clrMediumVioletRed
Web Colors
clrMidnightBlue
Midnight Blue
Web Colors
clrMintCream
Mint Cream
Web Colors
clrMistyRose
Misty Rose
Web Colors
clrMoccasin
Moccasin
Web Colors
clrNavajoWhite
Navajo White
Web Colors
clrNavy
Navy
Web Colors
clrNONE
Absence of color
Other Constants
clrOldLace
Old Lace
Web Colors
clrOlive
Olive
Web Colors
clrOliveDrab
Olive Drab
Web Colors
clrOrange
Orange
Web Colors
clrOrangeRed
Orange Red
Web Colors
clrOrchid
Orchid
Web Colors
clrPaleGoldenrod
Pale Goldenrod
Web Colors
clrPaleGreen
Pale Green
Web Colors
clrPaleTurquoise
Pale Turquoise
Web Colors
clrPaleVioletRed
Web Colors
clrPapayaWhip
Papaya Whip
Web Colors
clrPeachPuff
Peach Puff
Web Colors
clrPeru
Peru
Web Colors
clrPink
Pink
Web Colors
clrPlum
Plum
Web Colors
clrPowderBlue
Powder Blue
Web Colors
clrPurple
Purple
Web Colors
clrRed
Red
Web Colors
clrRosyBrown
Rosy Brown
Web Colors
clrRoyalBlue
Royal Blue
Web Colors
clrSaddleBrown
Saddle Brown
Web Colors
clrSalmon
Salmon
Web Colors
clrSandyBrown
Sandy Brown
Web Colors
4208
clrSeaGreen
Sea Green
Web Colors
clrSeashell
Seashell
Web Colors
clrSienna
Sienna
Web Colors
clrSilver
Silver
Web Colors
clrSkyBlue
Sky Blue
Web Colors
clrSlateBlue
Slate Blue
Web Colors
clrSlateGray
Slate Gray
Web Colors
clrSnow
Snow
Web Colors
clrSpringGreen
Spring Green
Web Colors
clrSteelBlue
Steel Blue
Web Colors
clrTan
Tan
Web Colors
clrTeal
Teal
Web Colors
clrThistle
Thistle
Web Colors
clrTomato
Tomato
Web Colors
clrTurquoise
Turquoise
Web Colors
clrViolet
Violet
Web Colors
clrWheat
Wheat
Web Colors
clrWhite
White
Web Colors
clrWhiteSmoke
White Smoke
Web Colors
clrYellow
Yellow
Web Colors
clrYellowGreen
Yellow Green
Web Colors
CORNER_LEFT_LOWER
ObjectSetInteger,
ObjectGetInteger
CORNER_LEFT_UPPER
ObjectSetInteger,
ObjectGetInteger
CORNER_RIGHT_LOWER
ObjectSetInteger,
ObjectGetInteger
CORNER_RIGHT_UPPER
ObjectSetInteger,
ObjectGetInteger
CP_ACP
ANSI
CharArrayToString,
StringToCharArray, FileOpen
CP_MACCP
CharArrayToString,
StringToCharArray, FileOpen
4209
CharArrayToString,
StringToCharArray, FileOpen
CP_SYMBOL
CharArrayToString,
StringToCharArray, FileOpen
CP_THREAD_ACP
CharArrayToString,
StringToCharArray, FileOpen
CP_UTF7
CharArrayToString,
StringToCharArray, FileOpen
CP_UTF8
CharArrayToString,
StringToCharArray, FileOpen
CRYPT_AES128
CryptEncode, CryptDecode
CRYPT_AES256
CryptEncode, CryptDecode
CRYPT_ARCH_ZIP
ZIP archives
CryptEncode, CryptDecode
CRYPT_BASE64
BASE64
CryptEncode, CryptDecode
CRYPT_DES
CryptEncode, CryptDecode
CRYPT_HASH_MD5
CryptEncode, CryptDecode
CRYPT_HASH_SHA1
CryptEncode, CryptDecode
CRYPT_HASH_SHA256
CryptEncode, CryptDecode
DBL_DIG
DBL_EPSILON
DBL_MANT_DIG
DBL_MAX
DBL_MAX_10_EXP
DBL_MAX_EXP
4210
DBL_MIN
DBL_MIN_10_EXP
DBL_MIN_EXP
DEAL_COMMENT
Deal comment
HistoryDealGetString
DEAL_COMMISSION
Deal commission
HistoryDealGetDouble
DEAL_ENTRY
HistoryDealGetInteger
DEAL_ENTRY_IN
Entry in
HistoryDealGetInteger
DEAL_ENTRY_INOUT
Reverse
HistoryDealGetInteger
DEAL_ENTRY_OUT
Entry out
HistoryDealGetInteger
DEAL_MAGIC
DEAL_ORDER
HistoryDealGetInteger
DEAL_POSITION_ID
HistoryDealGetInteger
DEAL_PRICE
Deal price
HistoryDealGetDouble
DEAL_PROFIT
Deal profit
HistoryDealGetDouble
DEAL_SWAP
HistoryDealGetDouble
DEAL_SYMBOL
Deal symbol
HistoryDealGetString
DEAL_TIME
Deal time
HistoryDealGetInteger
DEAL_TIME_MSC
HistoryDealGetInteger
DEAL_TYPE
Deal type
HistoryDealGetInteger
DEAL_TYPE_BALANCE
Balance
HistoryDealGetInteger
DEAL_TYPE_BONUS
Bonus
HistoryDealGetInteger
(see
HistoryDealGetInteger
4211
DEAL_TYPE_BUY
Buy
HistoryDealGetInteger
DEAL_TYPE_BUY_CANCELED
HistoryDealGetInteger
DEAL_TYPE_CHARGE
Additional charge
HistoryDealGetInteger
DEAL_TYPE_COMMISSION
Additional commission
HistoryDealGetInteger
DEAL_TYPE_COMMISSION_AGE
NT_DAILY
HistoryDealGetInteger
DEAL_TYPE_COMMISSION_AGE
NT_MONTHLY
HistoryDealGetInteger
DEAL_TYPE_COMMISSION_DAI
LY
Daily commission
HistoryDealGetInteger
DEAL_TYPE_COMMISSION_MO
NTHLY
Monthly commission
HistoryDealGetInteger
DEAL_TYPE_CORRECTION
Correction
HistoryDealGetInteger
DEAL_TYPE_CREDIT
Credit
HistoryDealGetInteger
DEAL_TYPE_INTEREST
Interest rate
HistoryDealGetInteger
DEAL_TYPE_SELL
Sell
HistoryDealGetInteger
DEAL_TYPE_SELL_CANCELED
HistoryDealGetInteger
DEAL_VOLUME
Deal volume
HistoryDealGetDouble
4212
DRAW_ARROW
Drawing arrows
Drawing Styles
DRAW_BARS
Drawing Styles
DRAW_CANDLES
Display as a
candlesticks
Drawing Styles
DRAW_COLOR_ARROW
Drawing Styles
DRAW_COLOR_BARS
Multicolored bars
Drawing Styles
DRAW_COLOR_CANDLES
Multicolored candlesticks
Drawing Styles
DRAW_COLOR_HISTOGRAM
Drawing Styles
DRAW_COLOR_HISTOGRAM2
Drawing Styles
DRAW_COLOR_LINE
Multicolored line
Drawing Styles
DRAW_COLOR_SECTION
Multicolored section
Drawing Styles
DRAW_COLOR_ZIGZAG
Multicolored ZigZag
Drawing Styles
DRAW_FILLING
Drawing Styles
DRAW_HISTOGRAM
Drawing Styles
DRAW_HISTOGRAM2
Drawing Styles
DRAW_LINE
Line
Drawing Styles
DRAW_NONE
Not drawn
Drawing Styles
DRAW_SECTION
Section
Drawing Styles
DRAW_ZIGZAG
ELLIOTT_CYCLE
Cycle
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_GRAND_SUPERCYCLE
Grand Supercycle
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_INTERMEDIATE
Intermediate
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_MINOR
Minor
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_MINUETTE
Minuette
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_MINUTE
Minute
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_PRIMARY
Primary
ObjectSetInteger,
sequence
of
vertical
Drawing Styles
4213
ObjectGetInteger
ELLIOTT_SUBMINUETTE
Subminuette
ObjectSetInteger,
ObjectGetInteger
ELLIOTT_SUPERCYCLE
Supercycle
ObjectSetInteger,
ObjectGetInteger
EMPTY_VALUE
Other Constants
ERR_ACCOUNT_WRONG_PROP
ERTY
GetLastError
ERR_ARRAY_BAD_SIZE
GetLastError
ERR_ARRAY_RESIZE_ERROR
GetLastError
ERR_BOOKS_CANNOT_ADD
GetLastError
ERR_BOOKS_CANNOT_DELETE
GetLastError
ERR_BOOKS_CANNOT_GET
GetLastError
ERR_BOOKS_CANNOT_SUBSCRI
BE
GetLastError
ERR_BUFFERS_NO_MEMORY
GetLastError
ERR_BUFFERS_WRONG_INDEX
GetLastError
ERR_CANNOT_CLEAN_DIRECT
ORY
GetLastError
ERR_CANNOT_DELETE_DIRECT
ORY
The directory
removed
GetLastError
ERR_CANNOT_DELETE_FILE
GetLastError
ERR_CANNOT_OPEN_FILE
GetLastError
ERR_CHAR_ARRAY_ONLY
GetLastError
ERR_CHART_CANNOT_CHANG
E
GetLastError
ERR_CHART_CANNOT_CREATE
GetLastError
cannot
be
4214
_TIMER
ERR_CHART_CANNOT_OPEN
GetLastError
ERR_CHART_INDICATOR_CANN
OT_ADD
GetLastError
ERR_CHART_INDICATOR_CANN
OT_DEL
Error deleting an
from the chart
indicator
GetLastError
ERR_CHART_INDICATOR_NOT_
FOUND
GetLastError
ERR_CHART_NAVIGATE_FAILE
D
GetLastError
ERR_CHART_NO_EXPERT
GetLastError
ERR_CHART_NO_REPLY
GetLastError
ERR_CHART_NOT_FOUND
GetLastError
ERR_CHART_SCREENSHOT_FAI
LED
GetLastError
ERR_CHART_TEMPLATE_FAILE
D
GetLastError
ERR_CHART_WINDOW_NOT_F
OUND
Subwindow containing
indicator was not found
ERR_CHART_WRONG_ID
Wrong chart ID
GetLastError
ERR_CHART_WRONG_PARAME
TER
GetLastError
ERR_CHART_WRONG_PROPER
TY
GetLastError
ERR_CUSTOM_WRONG_PROPE
RTY
Wrong ID of the
indicator property
GetLastError
ERR_DIRECTORY_NOT_EXIST
GetLastError
ERR_DOUBLE_ARRAY_ONLY
GetLastError
ERR_FILE_BINSTRINGSIZE
GetLastError
ERR_FILE_CACHEBUFFER_ERR
OR
GetLastError
ERR_FILE_CANNOT_REWRITE
GetLastError
ERR_FILE_IS_DIRECTORY
GetLastError
the
custom
GetLastError
4215
ERR_FILE_ISNOT_DIRECTORY
GetLastError
ERR_FILE_NOT_EXIST
GetLastError
ERR_FILE_NOTBIN
GetLastError
ERR_FILE_NOTCSV
GetLastError
ERR_FILE_NOTTOREAD
GetLastError
ERR_FILE_NOTTOWRITE
GetLastError
ERR_FILE_NOTTXT
GetLastError
ERR_FILE_NOTTXTORCSV
GetLastError
ERR_FILE_READERROR
GetLastError
ERR_FILE_WRITEERROR
GetLastError
ERR_FLOAT_ARRAY_ONLY
GetLastError
ERR_FTP_SEND_FAILED
GetLastError
ERR_FUNCTION_NOT_ALLOWE
D
GetLastError
ERR_GLOBALVARIABLE_EXISTS
GetLastError
ERR_GLOBALVARIABLE_NOT_F
OUND
GetLastError
ERR_HISTORY_NOT_FOUND
GetLastError
ERR_HISTORY_WRONG_PROPE
RTY
Wrong ID
property
history
GetLastError
ERR_INCOMPATIBLE_ARRAYS
GetLastError
ERR_INCOMPATIBLE_FILE
GetLastError
ERR_INDICATOR_CANNOT_ADD
GetLastError
of
the
4216
ERR_INDICATOR_CANNOT_APP
LY
GetLastError
ERR_INDICATOR_CANNOT_CRE
ATE
GetLastError
ERR_INDICATOR_CUSTOM_NA
ME
GetLastError
ERR_INDICATOR_DATA_NOT_F
OUND
GetLastError
ERR_INDICATOR_NO_MEMORY
GetLastError
ERR_INDICATOR_PARAMETER_
TYPE
GetLastError
ERR_INDICATOR_PARAMETERS
_MISSING
GetLastError
ERR_INDICATOR_UNKNOWN_S
YMBOL
Unknown symbol
GetLastError
ERR_INDICATOR_WRONG_HAN
DLE
GetLastError
ERR_INDICATOR_WRONG_INDE
X
GetLastError
ERR_INDICATOR_WRONG_PAR
AMETERS
GetLastError
ERR_INT_ARRAY_ONLY
GetLastError
ERR_INTERNAL_ERROR
GetLastError
ERR_INVALID_ARRAY
GetLastError
ERR_INVALID_DATETIME
GetLastError
ERR_INVALID_FILEHANDLE
GetLastError
ERR_INVALID_PARAMETER
GetLastError
ERR_INVALID_POINTER
Wrong pointer
GetLastError
ERR_INVALID_POINTER_TYPE
GetLastError
ERR_LONG_ARRAY_ONLY
GetLastError
ERR_MAIL_SEND_FAILED
GetLastError
4217
ERR_MARKET_LASTTIME_UNKN
OWN
GetLastError
ERR_MARKET_NOT_SELECTED
in
GetLastError
ERR_MARKET_SELECT_ERROR
GetLastError
ERR_MARKET_UNKNOWN_SYM
BOL
Unknown symbol
GetLastError
ERR_MARKET_WRONG_PROPE
RTY
GetLastError
ERR_MQL5_WRONG_PROPERT
Y
Wrong identifier
program property
GetLastError
ERR_NO_STRING_DATE
GetLastError
ERR_NOT_ENOUGH_MEMORY
GetLastError
ERR_NOTIFICATION_SEND_FAI
LED
GetLastError
ERR_NOTIFICATION_TOO_FRE
QUENT
Too frequent
notifications
of
GetLastError
ERR_NOTIFICATION_WRONG_P
ARAMETER
GetLastError
ERR_NOTIFICATION_WRONG_S
ETTINGS
Wrong
settings
of
notifications in the terminal
(ID is not specified or
permission is not set)
GetLastError
ERR_NOTINITIALIZED_STRING
GetLastError
ERR_NUMBER_ARRAYS_ONLY
GetLastError
ERR_OBJECT_ERROR
GetLastError
ERR_OBJECT_GETDATE_FAILE
D
Unable
to
get
date
corresponding to the value
GetLastError
ERR_OBJECT_GETVALUE_FAIL
ED
Unable
to
get
value
corresponding to the date
GetLastError
ERR_OBJECT_NOT_FOUND
GetLastError
ERR_OBJECT_WRONG_PROPER
TY
GetLastError
ERR_ONEDIM_ARRAYS_ONLY
Must be a one-dimensional
GetLastError
of
sending
the
4218
array
ERR_OPENCL_BUFFER_CREATE
GetLastError
ERR_OPENCL_CONTEXT_CREA
TE
Error creating
context
OpenCL
GetLastError
ERR_OPENCL_EXECUTE
GetLastError
ERR_OPENCL_INTERNAL
GetLastError
ERR_OPENCL_INVALID_HANDL
E
GetLastError
ERR_OPENCL_KERNEL_CREATE
Error creating
kernel
OpenCL
GetLastError
ERR_OPENCL_NOT_SUPPORTE
D
GetLastError
ERR_OPENCL_PROGRAM_CREA
TE
GetLastError
ERR_OPENCL_QUEUE_CREATE
GetLastError
ERR_OPENCL_SET_KERNEL_PA
RAMETER
GetLastError
ERR_OPENCL_TOO_LONG_KER
NEL_NAME
GetLastError
ERR_OPENCL_WRONG_BUFFER
_OFFSET
GetLastError
ERR_OPENCL_WRONG_BUFFER
_SIZE
GetLastError
ERR_PLAY_SOUND_FAILED
GetLastError
ERR_RESOURCE_NAME_DUPLIC
ATED
GetLastError
ERR_RESOURCE_NAME_IS_TO
O_LONG
GetLastError
ERR_RESOURCE_NOT_FOUND
GetLastError
ERR_RESOURCE_UNSUPPOTED
_TYPE
GetLastError
ERR_SERIES_ARRAY
GetLastError
ERR_SHORT_ARRAY_ONLY
GetLastError
the
an
4219
ERR_SMALL_ARRAY
GetLastError
ERR_SMALL_ASSERIES_ARRAY
GetLastError
ERR_STRING_OUT_OF_MEMOR
Y
GetLastError
ERR_STRING_RESIZE_ERROR
GetLastError
ERR_STRING_SMALL_LEN
GetLastError
ERR_STRING_TIME_ERROR
GetLastError
ERR_STRING_TOO_BIGNUMBER
GetLastError
ERR_STRING_UNKNOWNTYPE
when
GetLastError
ERR_STRING_ZEROADDED
GetLastError
ERR_STRINGPOS_OUTOFRANG
E
GetLastError
ERR_STRUCT_WITHOBJECTS_
ORCLASS
GetLastError
ERR_SUCCESS
The
operation
successfully
GetLastError
ERR_TERMINAL_WRONG_PROP
ERTY
Wrong identifier
terminal property
ERR_TOO_LONG_FILENAME
GetLastError
ERR_TOO_MANY_FILES
GetLastError
ERR_TOO_MANY_FORMATTER
S
GetLastError
ERR_TOO_MANY_PARAMETERS
GetLastError
ERR_TRADE_DEAL_NOT_FOUN
D
GetLastError
ERR_TRADE_DISABLED
GetLastError
ERR_TRADE_ORDER_NOT_FOU
GetLastError
completed
of
the
GetLastError
4220
ND
ERR_TRADE_POSITION_NOT_F
OUND
GetLastError
ERR_TRADE_SEND_FAILED
GetLastError
ERR_TRADE_WRONG_PROPER
TY
GetLastError
ERR_USER_ERROR_FIRST
GetLastError
ERR_WEBREQUEST_CONNECT_
FAILED
GetLastError
ERR_WEBREQUEST_INVALID_A
DDRESS
Invalid URL
GetLastError
ERR_WEBREQUEST_REQUEST_
FAILED
GetLastError
ERR_WEBREQUEST_TIMEOUT
Timeout exceeded
GetLastError
ERR_WRONG_DIRECTORYNAM
E
GetLastError
ERR_WRONG_FILEHANDLE
GetLastError
ERR_WRONG_FILENAME
GetLastError
ERR_WRONG_FORMATSTRING
GetLastError
ERR_WRONG_INTERNAL_PARA
METER
GetLastError
ERR_WRONG_STRING_DATE
GetLastError
ERR_WRONG_STRING_OBJECT
GetLastError
ERR_WRONG_STRING_PARAME
TER
GetLastError
ERR_WRONG_STRING_TIME
GetLastError
ERR_ZEROSIZE_ARRAY
GetLastError
FILE_ACCESS_DATE
FileGetInteger
FILE_ANSI
FileOpen
FILE_BIN
Binary
read/write
mode
(without string to string
conversion). Flag is used in
FileOpen().
FileOpen
4221
FILE_COMMON
FILE_CREATE_DATE
Date of creation
FileGetInteger
FILE_CSV
FileOpen
FILE_END
FileGetInteger
FILE_EXISTS
FileGetInteger
FILE_IS_ANSI
FileGetInteger
FILE_IS_BINARY
FileGetInteger
FILE_IS_COMMON
FileGetInteger
FILE_IS_CSV
FileGetInteger
FILE_IS_READABLE
FileGetInteger
FILE_IS_TEXT
FileGetInteger
FILE_IS_WRITABLE
FileGetInteger
FILE_LINE_END
FileGetInteger
FILE_MODIFY_DATE
FileGetInteger
FILE_POSITION
FileGetInteger
FILE_READ
FileOpen
FILE_REWRITE
FileCopy, FileMove
4222
FileOpen
FILE_SHARE_WRITE
FileOpen
FILE_SIZE
FileGetInteger
FILE_TXT
FileOpen
FILE_UNICODE
FileOpen
FILE_WRITE
FileOpen
FLT_DIG
FLT_EPSILON
FLT_MANT_DIG
FLT_MAX
FLT_MAX_10_EXP
FLT_MAX_EXP
4223
FLT_MIN
FLT_MIN_10_EXP
FLT_MIN_EXP
FRIDAY
Friday
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
GANN_DOWN_TREND
Line corresponding
downward trend
to
the
ObjectSetInteger,
ObjectGetInteger
GANN_UP_TREND
Line corresponding
uptrend line
to
the
ObjectSetInteger,
ObjectGetInteger
GATORJAW_LINE
Jaw line
Indicators Lines
GATORLIPS_LINE
Lips line
Indicators Lines
GATORTEETH_LINE
Teeth line
Indicators Lines
IDABORT
"Abort"
pressed
IDCANCEL
"Cancel"
pressed
button
has
been
MessageBox
has
been
MessageBox
IDCONTINUE
MessageBox
IDIGNORE
"Ignore"
pressed
MessageBox
IDNO
MessageBox
IDOK
MessageBox
IDRETRY
"Retry"
pressed
been
MessageBox
IDTRYAGAIN
MessageBox
IDYES
MessageBox
IND_AC
Accelerator Oscillator
IndicatorCreate,
IndicatorParameters
IND_AD
Accumulation/Distribution
IndicatorCreate,
IndicatorParameters
IND_ADX
IndicatorCreate,
IndicatorParameters
button
button
button
has
has
been
4224
IND_ADXW
IndicatorCreate,
IndicatorParameters
IND_ALLIGATOR
Alligator
IndicatorCreate,
IndicatorParameters
IND_AMA
IndicatorCreate,
IndicatorParameters
IND_AO
Awesome Oscillator
IndicatorCreate,
IndicatorParameters
IND_ATR
IndicatorCreate,
IndicatorParameters
IND_BANDS
Bollinger Bands
IndicatorCreate,
IndicatorParameters
IND_BEARS
Bears Power
IndicatorCreate,
IndicatorParameters
IND_BULLS
Bulls Power
IndicatorCreate,
IndicatorParameters
IND_BWMFI
IndicatorCreate,
IndicatorParameters
IND_CCI
IndicatorCreate,
IndicatorParameters
IND_CHAIKIN
Chaikin Oscillator
IndicatorCreate,
IndicatorParameters
IND_CUSTOM
Custom indicator
IndicatorCreate,
IndicatorParameters
IND_DEMA
Double Exponential
Average
IND_DEMARKER
DeMarker
IndicatorCreate,
IndicatorParameters
IND_ENVELOPES
Envelopes
IndicatorCreate,
IndicatorParameters
IND_FORCE
Force Index
IndicatorCreate,
IndicatorParameters
IND_FRACTALS
Fractals
IndicatorCreate,
IndicatorParameters
IND_FRAMA
Fractal
Average
IND_GATOR
Gator Oscillator
IndicatorCreate,
IndicatorParameters
IND_ICHIMOKU
IndicatorCreate,
IndicatorParameters
Adaptive
Moving
Moving
IndicatorCreate,
IndicatorParameters
IndicatorCreate,
IndicatorParameters
4225
IND_MA
Moving Average
IndicatorCreate,
IndicatorParameters
IND_MACD
MACD
IndicatorCreate,
IndicatorParameters
IND_MFI
IndicatorCreate,
IndicatorParameters
IND_MOMENTUM
Momentum
IndicatorCreate,
IndicatorParameters
IND_OBV
On Balance Volume
IndicatorCreate,
IndicatorParameters
IND_OSMA
OsMA
IndicatorCreate,
IndicatorParameters
IND_RSI
IndicatorCreate,
IndicatorParameters
IND_RVI
IndicatorCreate,
IndicatorParameters
IND_SAR
Parabolic SAR
IndicatorCreate,
IndicatorParameters
IND_STDDEV
Standard Deviation
IndicatorCreate,
IndicatorParameters
IND_STOCHASTIC
Stochastic Oscillator
IndicatorCreate,
IndicatorParameters
IND_TEMA
Triple Exponential
Average
Moving
IndicatorCreate,
IndicatorParameters
IND_TRIX
Triple Exponential
Averages Oscillator
Moving
IndicatorCreate,
IndicatorParameters
IND_VIDYA
Variable
Average
Dynamic
IndicatorCreate,
IndicatorParameters
IND_VOLUMES
Volumes
IndicatorCreate,
IndicatorParameters
IND_WPR
IndicatorCreate,
IndicatorParameters
INDICATOR_CALCULATIONS
Auxiliary
buffers
intermediate calculations
INDICATOR_COLOR_INDEX
Color
SetIndexBuffer
INDICATOR_DATA
Data to draw
SetIndexBuffer
INDICATOR_DIGITS
Accuracy
of
drawing
indicator values
of
IndicatorSetInteger
INDICATOR_HEIGHT
IndicatorSetInteger
Index
for
SetIndexBuffer
4226
IndicatorSetInteger
INDICATOR_LEVELS
Number of levels
indicator window
INDICATOR_LEVELSTYLE
IndicatorSetInteger
INDICATOR_LEVELTEXT
Level description
IndicatorSetString
INDICATOR_LEVELVALUE
Level value
IndicatorSetDouble
INDICATOR_LEVELWIDTH
IndicatorSetInteger
INDICATOR_MAXIMUM
Maximum
window
of
the
indicator
IndicatorSetDouble
INDICATOR_MINIMUM
Minimum
window
of
the
indicator
IndicatorSetDouble
INDICATOR_SHORTNAME
IndicatorSetString
INT_MAX
INT_MIN
INVALID_HANDLE
Incorrect handle
Other Constants
IS_DEBUG_MODE
Other Constants
IS_PROFILE_MODE
Other Constants
KIJUNSEN_LINE
Kijun-sen line
Indicators Lines
LICENSE_DEMO
MQLInfoInteger
LICENSE_FREE
MQLInfoInteger
LICENSE_FULL
MQLInfoInteger
LICENSE_TIME
MQLInfoInteger
LONG_MAX
in
the
IndicatorSetInteger
4227
LOWER_BAND
Lower limit
Indicators Lines
LOWER_HISTOGRAM
Bottom histogram
Indicators Lines
LOWER_LINE
Bottom line
Indicators Lines
M_1_PI
1/pi
Mathematical Constants
M_2_PI
2/pi
Mathematical Constants
M_2_SQRTPI
2/sqrt(pi)
Mathematical Constants
M_E
Mathematical Constants
M_LN10
ln(10)
Mathematical Constants
M_LN2
ln(2)
Mathematical Constants
M_LOG10E
log10(e)
Mathematical Constants
M_LOG2E
log2(e)
Mathematical Constants
M_PI
pi
Mathematical Constants
M_PI_2
pi/2
Mathematical Constants
M_PI_4
pi/4
Mathematical Constants
M_SQRT1_2
1/sqrt(2)
Mathematical Constants
M_SQRT2
sqrt(2)
Mathematical Constants
MAIN_LINE
Main line
Indicators Lines
MB_ABORTRETRYIGNORE
MessageBox
MB_CANCELTRYCONTINUE
MessageBox
MB_DEFBUTTON1
The
first
button
MB_DEFBUTTON1 - is default,
if
the
other
buttons
MB_DEFBUTTON2,
MB_DEFBUTTON3,
or
MB_DEFBUTTON4
are
not
specified
MessageBox
MB_DEFBUTTON2
MessageBox
MB_DEFBUTTON3
MessageBox
MB_DEFBUTTON4
MessageBox
4228
MB_ICONEXCLAMATION,
MB_ICONWARNING
MessageBox
MB_ICONINFORMATION,
MB_ICONASTERISK
MessageBox
MB_ICONQUESTION
MessageBox
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND
MessageBox
MB_OK
MessageBox
MB_OKCANCEL
MessageBox
MB_RETRYCANCEL
MessageBox
MB_YESNO
MessageBox
MB_YESNOCANCEL
MessageBox
MINUSDI_LINE
Line DI
Indicators Lines
MODE_EMA
Exponential averaging
Smoothing Methods
MODE_LWMA
Linear-weighted averaging
Smoothing Methods
MODE_SMA
Simple averaging
Smoothing Methods
MODE_SMMA
Smoothed averaging
Smoothing Methods
MONDAY
Monday
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
MQL_DEBUG
MQLInfoInteger
MQL_DLLS_ALLOWED
MQLInfoInteger
MQL_FRAME_MODE
MQLInfoInteger
MQL_LICENSE_TYPE
MQLInfoInteger
4229
_TYPE).
MQL_MEMORY_LIMIT
MQLInfoInteger
MQL_MEMORY_USED
MQLInfoInteger
MQL_OPTIMIZATION
MQLInfoInteger
MQL_PROFILER
MQLInfoInteger
MQL_PROGRAM_NAME
MQLInfoString
MQL_PROGRAM_PATH
MQLInfoString
MQL_PROGRAM_TYPE
MQLInfoInteger
MQL_SIGNALS_ALLOWED
MQLInfoInteger
MQL_TESTER
MQLInfoInteger
MQL_TRADE_ALLOWED
MQLInfoInteger
MQL_VISUAL_MODE
MQLInfoInteger
NULL
Other Constants
OBJ_ALL_PERIODS
ObjectSetInteger,
ObjectGetInteger
OBJ_ARROW
Arrow
Object Types
OBJ_ARROW_BUY
Buy Sign
Object Types
OBJ_ARROW_CHECK
Check Sign
Object Types
OBJ_ARROW_DOWN
Arrow Down
Object Types
OBJ_ARROW_LEFT_PRICE
Object Types
OBJ_ARROW_RIGHT_PRICE
Object Types
OBJ_ARROW_SELL
Sell Sign
Object Types
OBJ_ARROW_STOP
Stop Sign
Object Types
OBJ_ARROW_THUMB_DOWN
Thumbs Down
Object Types
4230
OBJ_ARROW_THUMB_UP
Thumbs Up
Object Types
OBJ_ARROW_UP
Arrow Up
Object Types
OBJ_ARROWED_LINE
Arrowed Line
Object Types
OBJ_BITMAP
Bitmap
Object Types
OBJ_BITMAP_LABEL
Bitmap Label
Object Types
OBJ_BUTTON
Button
Object Types
OBJ_CHANNEL
Equidistant Channel
Object Types
OBJ_CHART
Chart
Object Types
OBJ_CYCLES
Cycle Lines
Object Types
OBJ_EDIT
Edit
Object Types
OBJ_ELLIOTWAVE3
Object Types
OBJ_ELLIOTWAVE5
Object Types
OBJ_ELLIPSE
Ellipse
Object Types
OBJ_EVENT
The
"Event"
object
corresponding to an event in
the economic calendar
Object Types
OBJ_EXPANSION
Fibonacci Expansion
Object Types
OBJ_FIBO
Fibonacci Retracement
Object Types
OBJ_FIBOARC
Fibonacci Arcs
Object Types
OBJ_FIBOCHANNEL
Fibonacci Channel
Object Types
OBJ_FIBOFAN
Fibonacci Fan
Object Types
OBJ_FIBOTIMES
Object Types
OBJ_GANNFAN
Gann Fan
Object Types
OBJ_GANNGRID
Gann Grid
Object Types
OBJ_GANNLINE
Gann Line
Object Types
OBJ_HLINE
Horizontal Line
Object Types
OBJ_LABEL
Label
Object Types
OBJ_NO_PERIODS
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_D1
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H1
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H12
ObjectSetInteger,
ObjectGetInteger
4231
OBJ_PERIOD_H2
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H3
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H4
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H6
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_H8
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M1
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M10
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M12
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M15
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M2
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M20
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M3
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M30
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M4
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M5
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_M6
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_MN1
ObjectSetInteger,
ObjectGetInteger
OBJ_PERIOD_W1
ObjectSetInteger,
ObjectGetInteger
OBJ_PITCHFORK
Andrews Pitchfork
Object Types
OBJ_RECTANGLE
Rectangle
Object Types
OBJ_RECTANGLE_LABEL
Object Types
4232
Object Types
OBJ_STDDEVCHANNEL
Object Types
OBJ_TEXT
Text
Object Types
OBJ_TREND
Trend Line
Object Types
OBJ_TRENDBYANGLE
Object Types
OBJ_TRIANGLE
Triangle
Object Types
OBJ_VLINE
Vertical Line
Object Types
OBJPROP_ALIGN
ObjectSetInteger,
ObjectGetInteger
OBJPROP_ANCHOR
ObjectSetInteger,
ObjectGetInteger
OBJPROP_ANGLE
ObjectSetDouble,
ObjectGetDouble
OBJPROP_ARROWCODE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_BACK
ObjectSetInteger,
ObjectGetInteger
OBJPROP_BGCOLOR
ObjectSetInteger,
ObjectGetInteger
OBJPROP_BMPFILE
ObjectSetString,
ObjectGetString
OBJPROP_BORDER_COLOR
ObjectSetInteger,
ObjectGetInteger
OBJPROP_BORDER_TYPE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_CHART_ID
ObjectSetInteger,
ObjectGetInteger
OBJPROP_CHART_SCALE
ObjectSetInteger,
ObjectGetInteger
4233
OBJPROP_COLOR
Color
ObjectSetInteger,
ObjectGetInteger
OBJPROP_CORNER
ObjectSetInteger,
ObjectGetInteger
OBJPROP_CREATETIME
ObjectSetInteger,
ObjectGetInteger
OBJPROP_DATE_SCALE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_DEGREE
Wave
ObjectSetInteger,
ObjectGetInteger
OBJPROP_DEVIATION
ObjectSetDouble,
ObjectGetDouble
OBJPROP_DIRECTION
ObjectSetInteger,
ObjectGetInteger
OBJPROP_DRAWLINES
ObjectSetInteger,
ObjectGetInteger
OBJPROP_ELLIPSE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_FILL
ObjectSetInteger,
ObjectGetInteger
OBJPROP_FONT
Font
ObjectSetString,
ObjectGetString
OBJPROP_FONTSIZE
Font size
ObjectSetInteger,
ObjectGetInteger
OBJPROP_HIDDEN
ObjectSetInteger,
ObjectGetInteger
4234
objects" window.
OBJPROP_LEVELCOLOR
ObjectSetInteger,
ObjectGetInteger
OBJPROP_LEVELS
Number of levels
ObjectSetInteger,
ObjectGetInteger
OBJPROP_LEVELSTYLE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_LEVELTEXT
Level description
ObjectSetString,
ObjectGetString
OBJPROP_LEVELVALUE
Level value
ObjectSetDouble,
ObjectGetDouble
OBJPROP_LEVELWIDTH
ObjectSetInteger,
ObjectGetInteger
OBJPROP_NAME
Object name
ObjectSetString,
ObjectGetString
OBJPROP_PERIOD
Timeframe
object
OBJPROP_PRICE
Price coordinate
ObjectSetDouble,
ObjectGetDouble
OBJPROP_PRICE_SCALE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_RAY
ObjectSetInteger,
ObjectGetInteger
OBJPROP_RAY_LEFT
ObjectSetInteger,
ObjectGetInteger
OBJPROP_RAY_RIGHT
ObjectSetInteger,
ObjectGetInteger
OBJPROP_READONLY
ObjectSetInteger,
ObjectGetInteger
OBJPROP_SCALE
ObjectSetDouble,
ObjectGetDouble
OBJPROP_SELECTABLE
Object availability
ObjectSetInteger,
ObjectGetInteger
OBJPROP_SELECTED
Object is selected
ObjectSetInteger,
ObjectGetInteger
OBJPROP_STATE
Button state
depressed)
OBJPROP_STYLE
Style
for
the
Chart
(pressed
ObjectSetInteger,
ObjectGetInteger
ObjectSetInteger,
ObjectGetInteger
ObjectSetInteger,
ObjectGetInteger
4235
OBJPROP_SYMBOL
ObjectSetString,
ObjectGetString
OBJPROP_TEXT
ObjectSetString,
ObjectGetString
OBJPROP_TIME
Time coordinate
ObjectSetInteger,
ObjectGetInteger
OBJPROP_TIMEFRAMES
Visibility of
timeframes
OBJPROP_TOOLTIP
ObjectSetString,
ObjectGetString
OBJPROP_TYPE
Object type
ObjectSetInteger,
ObjectGetInteger
OBJPROP_WIDTH
Line thickness
ObjectSetInteger,
ObjectGetInteger
OBJPROP_XDISTANCE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_XOFFSET
ObjectSetInteger,
ObjectGetInteger
OBJPROP_XSIZE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_YDISTANCE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_YOFFSET
ObjectSetInteger,
an
object
at
ObjectSetInteger,
ObjectGetInteger
4236
ObjectGetInteger
OBJPROP_YSIZE
ObjectSetInteger,
ObjectGetInteger
OBJPROP_ZORDER
ObjectSetInteger,
ObjectGetInteger
ORDER_COMMENT
Order comment
OrderGetString,
HistoryOrderGetString
ORDER_FILLING_FOK
OrderGetInteger,
HistoryOrderGetInteger
ORDER_FILLING_IOC
OrderGetInteger,
HistoryOrderGetInteger
4237
OrderGetInteger,
HistoryOrderGetInteger
ORDER_MAGIC
OrderGetInteger,
HistoryOrderGetInteger
ORDER_POSITION_ID
OrderGetInteger,
HistoryOrderGetInteger
ORDER_PRICE_CURRENT
OrderGetDouble,
HistoryOrderGetDouble
4238
ORDER_PRICE_OPEN
OrderGetDouble,
HistoryOrderGetDouble
ORDER_PRICE_STOPLIMIT
OrderGetDouble,
HistoryOrderGetDouble
ORDER_SL
OrderGetDouble,
HistoryOrderGetDouble
ORDER_STATE
Order state
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_CANCELED
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_EXPIRED
Order expired
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_FILLED
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_PARTIAL
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_PLACED
Order accepted
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_REJECTED
Order rejected
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_REQUEST_ADD
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_REQUEST_CAN
CEL
Order
is
being
deleted
(deleting from the trading
system)
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_REQUEST_MOD
IFY
OrderGetInteger,
HistoryOrderGetInteger
ORDER_STATE_STARTED
OrderGetInteger,
HistoryOrderGetInteger
ORDER_SYMBOL
OrderGetString,
HistoryOrderGetString
ORDER_TIME_DAY
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_DONE
Order
execution
cancellation time
or
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_DONE_MSC
Order execution/cancellation
time in milliseconds since
01.01.1970
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_EXPIRATION
OrderGetInteger,
HistoryOrderGetInteger
4239
ORDER_TIME_GTC
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_SETUP
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_SETUP_MSC
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_SPECIFIED
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TIME_SPECIFIED_DAY
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TP
OrderGetDouble,
HistoryOrderGetDouble
ORDER_TYPE
Order type
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_BUY
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_BUY_LIMIT
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_BUY_STOP
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_BUY_STOP_LIMI
T
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_FILLING
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_SELL
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_SELL_LIMIT
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_SELL_STOP
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_SELL_STOP_LIMI
T
OrderGetInteger,
HistoryOrderGetInteger
ORDER_TYPE_TIME
Order lifetime
OrderGetInteger,
HistoryOrderGetInteger
4240
ORDER_VOLUME_CURRENT
OrderGetDouble,
HistoryOrderGetDouble
ORDER_VOLUME_INITIAL
OrderGetDouble,
HistoryOrderGetDouble
PERIOD_CURRENT
Current timeframe
Chart Timeframes
PERIOD_D1
1 day
Chart Timeframes
PERIOD_H1
1 hour
Chart Timeframes
PERIOD_H12
12 hours
Chart Timeframes
PERIOD_H2
2 hours
Chart Timeframes
PERIOD_H3
3 hours
Chart Timeframes
PERIOD_H4
4 hours
Chart Timeframes
PERIOD_H6
6 hours
Chart Timeframes
PERIOD_H8
8 hours
Chart Timeframes
PERIOD_M1
1 minute
Chart Timeframes
PERIOD_M10
10 minutes
Chart Timeframes
PERIOD_M12
12 minutes
Chart Timeframes
PERIOD_M15
15 minutes
Chart Timeframes
PERIOD_M2
2 minutes
Chart Timeframes
PERIOD_M20
20 minutes
Chart Timeframes
PERIOD_M3
3 minutes
Chart Timeframes
PERIOD_M30
30 minutes
Chart Timeframes
PERIOD_M4
4 minutes
Chart Timeframes
PERIOD_M5
5 minutes
Chart Timeframes
PERIOD_M6
6 minutes
Chart Timeframes
PERIOD_MN1
1 month
Chart Timeframes
PERIOD_W1
1 week
Chart Timeframes
PLOT_ARROW
Arrow
code
DRAW_ARROW
style
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_ARROW_SHIFT
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_COLOR_INDEXES
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_DRAW_BEGIN
PlotIndexSetInteger,
PlotIndexGetInteger
for
4241
PLOT_DRAW_TYPE
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_EMPTY_VALUE
PlotIndexSetDouble
PLOT_LABEL
PlotIndexSetString
PLOT_LINE_COLOR
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_LINE_STYLE
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_LINE_WIDTH
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_SHIFT
PlotIndexSetInteger,
PlotIndexGetInteger
PLOT_SHOW_DATA
PlotIndexSetInteger,
PlotIndexGetInteger
PLUSDI_LINE
Line +DI
Indicators Lines
POINTER_AUTOMATIC
CheckPointer
POINTER_DYNAMIC
CheckPointer
POINTER_INVALID
Incorrect pointer
CheckPointer
POSITION_COMMENT
Position comment
PositionGetString
POSITION_COMMISSION
Commission
PositionGetDouble
POSITION_IDENTIFIER
PositionGetInteger
POSITION_MAGIC
PositionGetInteger
4242
ORDER_MAGIC)
POSITION_PRICE_CURRENT
PositionGetDouble
POSITION_PRICE_OPEN
PositionGetDouble
POSITION_PROFIT
Current profit
PositionGetDouble
POSITION_SL
PositionGetDouble
POSITION_SWAP
Cumulative swap
PositionGetDouble
POSITION_SYMBOL
PositionGetString
POSITION_TIME
PositionGetInteger
POSITION_TIME_MSC
PositionGetInteger
POSITION_TIME_UPDATE
in
PositionGetInteger
POSITION_TIME_UPDATE_MSC
PositionGetInteger
POSITION_TP
PositionGetDouble
POSITION_TYPE
Position type
PositionGetInteger
POSITION_TYPE_BUY
Buy
PositionGetInteger
POSITION_TYPE_SELL
Sell
PositionGetInteger
POSITION_VOLUME
Position volume
PositionGetDouble
PRICE_CLOSE
Close price
Price Constants
PRICE_HIGH
Price Constants
PRICE_LOW
Price Constants
PRICE_MEDIAN
Price Constants
PRICE_OPEN
Open price
Price Constants
PRICE_TYPICAL
Price Constants
PRICE_WEIGHTED
Price Constants
PROGRAM_EXPERT
Expert
MQLInfoInteger
PROGRAM_INDICATOR
Indicator
MQLInfoInteger
PROGRAM_SCRIPT
Script
MQLInfoInteger
4243
REASON_ACCOUNT
UninitializeReason, OnDeinit
REASON_CHARTCHANGE
UninitializeReason, OnDeinit
REASON_CHARTCLOSE
UninitializeReason, OnDeinit
REASON_CLOSE
UninitializeReason, OnDeinit
REASON_INITFAILED
UninitializeReason, OnDeinit
REASON_PARAMETERS
UninitializeReason, OnDeinit
REASON_PROGRAM
UninitializeReason, OnDeinit
REASON_RECOMPILE
UninitializeReason, OnDeinit
REASON_REMOVE
UninitializeReason, OnDeinit
REASON_TEMPLATE
SATURDAY
Saturday
SEEK_CUR
Current position of a
pointer
SEEK_END
File end
FileSeek
SEEK_SET
File beginning
FileSeek
SENKOUSPANA_LINE
Indicators Lines
SENKOUSPANB_LINE
Indicators Lines
SERIES_BARS_COUNT
SeriesInfoInteger
SERIES_FIRSTDATE
SeriesInfoInteger
SERIES_LASTBAR_DATE
SeriesInfoInteger
SERIES_SERVER_FIRSTDATE
SeriesInfoInteger
deleted
been
UninitializeReason, OnDeinit
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
file
FileSeek
4244
server regardless
timeframe
of
the
SERIES_SYNCHRONIZED
Symbol/period
data
synchronization flag for the
current moment
SeriesInfoInteger
SERIES_TERMINAL_FIRSTDATE
SeriesInfoInteger
SHORT_MAX
SHORT_MIN
SIGNAL_BASE_AUTHOR_LOGIN
Author login
SignalBaseGetString
SIGNAL_BASE_BALANCE
Account balance
SignalBaseGetDouble
SIGNAL_BASE_BROKER
SignalBaseGetString
SIGNAL_BASE_BROKER_SERVE
R
Broker server
SignalBaseGetString
SIGNAL_BASE_CURRENCY
SignalBaseGetString
SIGNAL_BASE_DATE_PUBLISHE
D
SignalBaseGetInteger
SIGNAL_BASE_DATE_STARTED
SignalBaseGetInteger
SIGNAL_BASE_EQUITY
Account equity
SignalBaseGetDouble
SIGNAL_BASE_GAIN
Account gain
SignalBaseGetDouble
SIGNAL_BASE_ID
Signal ID
SignalBaseGetInteger
SIGNAL_BASE_LEVERAGE
Account leverage
SignalBaseGetInteger
SIGNAL_BASE_MAX_DRAWDO
WN
SignalBaseGetDouble
SIGNAL_BASE_NAME
Signal name
SignalBaseGetString
SIGNAL_BASE_PIPS
Profit in pips
SignalBaseGetInteger
SIGNAL_BASE_PRICE
SignalBaseGetDouble
SIGNAL_BASE_RATING
Position in rating
SignalBaseGetInteger
SIGNAL_BASE_ROI
SignalBaseGetDouble
SIGNAL_BASE_SUBSCRIBERS
Number of subscribers
SignalBaseGetInteger
SIGNAL_BASE_TRADE_MODE
SignalBaseGetInteger
4245
SIGNAL_BASE_TRADES
Number of trades
SignalBaseGetInteger
SIGNAL_INFO_CONFIRMATION
S_DISABLED
The
flag
synchronization
confirmation dialog
SIGNAL_INFO_COPY_SLTP
SIGNAL_INFO_DEPOSIT_PERCE
NT
SignalInfoGetInteger,
SignalInfoSetInteger
SIGNAL_INFO_EQUITY_LIMIT
Equity limit
SignalInfoGetDouble,
SignalInfoSetDouble
SIGNAL_INFO_ID
SignalInfoGetInteger,
SignalInfoSetInteger
SIGNAL_INFO_NAME
SignalInfoGetString
SIGNAL_INFO_SLIPPAGE
SignalInfoGetDouble,
SignalInfoSetDouble
SIGNAL_INFO_SUBSCRIPTION_
ENABLED
SignalInfoGetInteger,
SignalInfoSetInteger
SIGNAL_INFO_TERMS_AGREE
SignalInfoGetInteger,
SignalInfoSetInteger
SIGNAL_INFO_VOLUME_PERCE
NT
SignalInfoGetDouble,
SignalInfoSetDouble
SIGNAL_LINE
Signal line
Indicators Lines
STAT_BALANCE_DD
TesterStatistics
STAT_BALANCE_DD_RELATIVE
TesterStatistics
STAT_BALANCE_DDREL_PERCE
NT
TesterStatistics
enables
without
SignalInfoGetInteger,
SignalInfoSetInteger
and Take
SignalInfoGetInteger,
SignalInfoSetInteger
4246
Balance drawdown as
a
percentage that was recorded
at the moment of the
maximum balance drawdown
in
monetary
terms
(STAT_BALANCE_DD).
TesterStatistics
STAT_BALANCEMIN
TesterStatistics
STAT_CONLOSSMAX
TesterStatistics
STAT_CONLOSSMAX_TRADES
TesterStatistics
STAT_CONPROFITMAX
TesterStatistics
STAT_CONPROFITMAX_TRADE
S
TesterStatistics
STAT_CUSTOM_ONTESTER
TesterStatistics
STAT_DEALS
TesterStatistics
STAT_EQUITY_DD
TesterStatistics
STAT_EQUITY_DD_RELATIVE
TesterStatistics
STAT_EQUITY_DDREL_PERCEN
TesterStatistics
4247
STAT_EQUITYDD_PERCENT
TesterStatistics
STAT_EQUITYMIN
TesterStatistics
STAT_EXPECTED_PAYOFF
Expected payoff
TesterStatistics
STAT_GROSS_LOSS
TesterStatistics
STAT_GROSS_PROFIT
TesterStatistics
STAT_INITIAL_DEPOSIT
TesterStatistics
STAT_LONG_TRADES
Long trades
TesterStatistics
STAT_LOSS_TRADES
Losing trades
TesterStatistics
STAT_LOSSTRADES_AVGCON
TesterStatistics
STAT_MAX_CONLOSS_TRADES
TesterStatistics
STAT_MAX_CONLOSSES
TesterStatistics
STAT_MAX_CONPROFIT_TRAD
ES
TesterStatistics
STAT_MAX_CONWINS
TesterStatistics
STAT_MAX_LOSSTRADE
TesterStatistics
STAT_MAX_PROFITTRADE
TesterStatistics
4248
TesterStatistics
STAT_PROFIT
TesterStatistics
STAT_PROFIT_FACTOR
TesterStatistics
STAT_PROFIT_LONGTRADES
TesterStatistics
STAT_PROFIT_SHORTTRADES
TesterStatistics
STAT_PROFIT_TRADES
Profitable trades
TesterStatistics
STAT_PROFITTRADES_AVGCO
N
TesterStatistics
STAT_RECOVERY_FACTOR
TesterStatistics
STAT_SHARPE_RATIO
Sharpe ratio
TesterStatistics
STAT_SHORT_TRADES
Short trades
TesterStatistics
STAT_TRADES
TesterStatistics
STAT_WITHDRAWAL
Money withdrawn
account
an
TesterStatistics
STO_CLOSECLOSE
Price Constants
STO_LOWHIGH
Price Constants
STYLE_DASH
Broken line
Drawing Styles
STYLE_DASHDOT
Dash-dot line
Drawing Styles
STYLE_DASHDOTDOT
Drawing Styles
STYLE_DOT
Dotted line
Drawing Styles
STYLE_SOLID
Solid line
Drawing Styles
SUNDAY
Sunday
SymbolInfoInteger,
from
4249
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
SYMBOL_ASK
SymbolInfoDouble
SYMBOL_ASKHIGH
SymbolInfoDouble
SYMBOL_ASKLOW
SymbolInfoDouble
SYMBOL_BANK
SymbolInfoString
SYMBOL_BASIS
SymbolInfoString
SYMBOL_BID
SymbolInfoDouble
SYMBOL_BIDHIGH
SymbolInfoDouble
SYMBOL_BIDLOW
SymbolInfoDouble
SYMBOL_CALC_MODE_CFD
SymbolInfoInteger
SYMBOL_CALC_MODE_CFDIND
EX
SymbolInfoInteger
SYMBOL_CALC_MODE_CFDLEV
ERAGE
CFD
Leverage
mode
calculation of margin and
profit for CFD at leverage
trading
SymbolInfoInteger
SYMBOL_CALC_MODE_EXCH_F
UTURES
SymbolInfoInteger
SYMBOL_CALC_MODE_EXCH_F
UTURES_FORTS
SymbolInfoInteger
SYMBOL_CALC_MODE_EXCH_S
TOCKS
SymbolInfoInteger
SYMBOL_CALC_MODE_FOREX
SymbolInfoInteger
SYMBOL_CALC_MODE_FUTURE
S
SymbolInfoInteger
SYMBOL_CALC_MODE_SERV_C
OLLATERAL
SymbolInfoInteger
SYMBOL_CURRENCY_BASE
SymbolInfoString
SYMBOL_CURRENCY_MARGIN
Margin currency
SymbolInfoString
4250
SYMBOL_CURRENCY_PROFIT
Profit currency
SymbolInfoString
SYMBOL_DESCRIPTION
Symbol description
SymbolInfoString
SYMBOL_DIGITS
SymbolInfoInteger
SYMBOL_EXPIRATION_DAY
SymbolInfoInteger
SYMBOL_EXPIRATION_GTC
SymbolInfoInteger
SYMBOL_EXPIRATION_MODE
Flags
of
allowed
expiration modes
SymbolInfoInteger
SYMBOL_EXPIRATION_SPECIFIE
D
The
expiration
time
specified in the order
is
SymbolInfoInteger
SYMBOL_EXPIRATION_SPECIFIE
D_DAY
The
expiration
date
specified in the order
is
SymbolInfoInteger
SYMBOL_EXPIRATION_TIME
SymbolInfoInteger
SYMBOL_FILLING_FOK
SymbolInfoInteger
SYMBOL_FILLING_IOC
SymbolInfoInteger
SYMBOL_FILLING_MODE
SymbolInfoInteger
SYMBOL_ISIN
SymbolInfoString
order
4251
Securities
Identification
Number). The International
Securities
Identification
Number
is
a
12-digit
alphanumeric
code
that
uniquely identifies a security.
The presence of this symbol
property is determined on the
side of a trade server.
SYMBOL_LAST
SymbolInfoDouble
SYMBOL_LASTHIGH
SymbolInfoDouble
SYMBOL_LASTLOW
SymbolInfoDouble
SYMBOL_MARGIN_INITIAL
SymbolInfoDouble
SYMBOL_MARGIN_MAINTENAN
CE
SymbolInfoDouble
SYMBOL_OPTION_MODE
Option type
SymbolInfoInteger
SYMBOL_OPTION_MODE_EURO
PEAN
SymbolInfoInteger
SYMBOL_OPTION_MODE_AMER
ICAN
SymbolInfoInteger
SYMBOL_OPTION_RIGHT
SymbolInfoInteger
SYMBOL_OPTION_RIGHT_CALL
SymbolInfoInteger
4252
SYMBOL_OPTION_RIGHT_PUT
SymbolInfoInteger
SYMBOL_OPTION_STRIKE
SymbolInfoDouble
SYMBOL_ORDER_LIMIT
SymbolInfoInteger
SYMBOL_ORDER_MARKET
SymbolInfoInteger
SYMBOL_ORDER_MODE
SymbolInfoInteger
SYMBOL_ORDER_SL
SymbolInfoInteger
SYMBOL_ORDER_STOP
SymbolInfoInteger
SYMBOL_ORDER_STOP_LIMIT
SymbolInfoInteger
SYMBOL_ORDER_TP
SymbolInfoInteger
SYMBOL_PATH
SymbolInfoString
SYMBOL_POINT
SymbolInfoDouble
SYMBOL_SELECT
SymbolInfoInteger
SYMBOL_SESSION_AW
SymbolInfoDouble
SYMBOL_SESSION_BUY_ORDER
S
SymbolInfoInteger
SYMBOL_SESSION_BUY_ORDER
S_VOLUME
SymbolInfoDouble
SYMBOL_SESSION_CLOSE
SymbolInfoDouble
SYMBOL_SESSION_DEALS
SymbolInfoInteger
SYMBOL_SESSION_INTEREST
SymbolInfoDouble
SYMBOL_SESSION_OPEN
SymbolInfoDouble
4253
SYMBOL_SESSION_PRICE_LIMI
T_MAX
SymbolInfoDouble
SYMBOL_SESSION_PRICE_LIMI
T_MIN
SymbolInfoDouble
SYMBOL_SESSION_PRICE_SETT
LEMENT
SymbolInfoDouble
SYMBOL_SESSION_SELL_ORDE
RS
SymbolInfoInteger
SYMBOL_SESSION_SELL_ORDE
RS_VOLUME
SymbolInfoDouble
SYMBOL_SESSION_TURNOVER
Summary turnover
current session
the
SymbolInfoDouble
SYMBOL_SESSION_VOLUME
SymbolInfoDouble
SYMBOL_SPREAD
SymbolInfoInteger
SYMBOL_SPREAD_FLOAT
SymbolInfoInteger
SYMBOL_START_TIME
SymbolInfoInteger
SYMBOL_SWAP_LONG
SymbolInfoDouble
SYMBOL_SWAP_MODE
SymbolInfoInteger
SYMBOL_SWAP_MODE_CURRE
NCY_DEPOSIT
SymbolInfoInteger
SYMBOL_SWAP_MODE_CURRE
NCY_MARGIN
SymbolInfoInteger
SYMBOL_SWAP_MODE_CURRE
NCY_SYMBOL
SymbolInfoInteger
SYMBOL_SWAP_MODE_DISABL
ED
SymbolInfoInteger
SYMBOL_SWAP_MODE_INTERE
ST_CURRENT
SymbolInfoInteger
SYMBOL_SWAP_MODE_INTERE
ST_OPEN
SymbolInfoInteger
SYMBOL_SWAP_MODE_POINTS
SymbolInfoInteger
of
4254
SYMBOL_SWAP_MODE_REOPEN
_BID
Swaps
are
charged
by
reopening positions. At the
end of a trading day the
position is closed. Next day it
is reopened by the current Bid
price +/- specified number of
points
(parameters
SYMBOL_SWAP_LONG
and
SYMBOL_SWAP_SHORT)
SymbolInfoInteger
SYMBOL_SWAP_MODE_REOPEN
_CURRENT
Swaps
are
charged
by
reopening positions. At the
end of a trading day the
position is closed. Next day it
is reopened by the close price
+/- specified number of points
(parameters
SYMBOL_SWAP_LONG
and
SYMBOL_SWAP_SHORT)
SymbolInfoInteger
SYMBOL_SWAP_ROLLOVER3DA
YS
SymbolInfoInteger
SYMBOL_SWAP_SHORT
SymbolInfoDouble
SYMBOL_TICKS_BOOKDEPTH
SymbolInfoInteger
SYMBOL_TIME
SymbolInfoInteger
SYMBOL_TRADE_CALC_MODE
Contract
mode
SymbolInfoInteger
SYMBOL_TRADE_CONTRACT_S
IZE
SymbolInfoDouble
SYMBOL_TRADE_EXECUTION_E
XCHANGE
Exchange execution
SymbolInfoInteger
SYMBOL_TRADE_EXECUTION_I
NSTANT
Instant execution
SymbolInfoInteger
SYMBOL_TRADE_EXECUTION_
MARKET
Market execution
SymbolInfoInteger
SYMBOL_TRADE_EXECUTION_R
EQUEST
price
calculation
Execution by request
SYMBOL_TRADE_EXEMODE
SYMBOL_TRADE_FREEZE_LEVE
L
Distance to freeze
operations in points
SymbolInfoInteger
SymbolInfoInteger
trade
SymbolInfoInteger
4255
SYMBOL_TRADE_MODE
SymbolInfoInteger
SYMBOL_TRADE_MODE_CLOSE
ONLY
SymbolInfoInteger
SYMBOL_TRADE_MODE_DISABL
ED
Trade is
symbol
SymbolInfoInteger
SYMBOL_TRADE_MODE_FULL
No trade restrictions
SymbolInfoInteger
SYMBOL_TRADE_MODE_LONG
ONLY
SymbolInfoInteger
SYMBOL_TRADE_MODE_SHORT
ONLY
SymbolInfoInteger
SYMBOL_TRADE_STOPS_LEVEL
SymbolInfoInteger
SYMBOL_TRADE_TICK_SIZE
SymbolInfoDouble
SYMBOL_TRADE_TICK_VALUE
Value
of
SYMBOL_TRADE_TICK_VALUE_
PROFIT
SymbolInfoDouble
SYMBOL_TRADE_TICK_VALUE_
LOSS
SymbolInfoDouble
SYMBOL_TRADE_TICK_VALUE_
PROFIT
SymbolInfoDouble
SYMBOL_VOLUME
SymbolInfoInteger
SYMBOL_VOLUME_LIMIT
SymbolInfoDouble
SYMBOL_VOLUME_MAX
SymbolInfoDouble
SYMBOL_VOLUME_MIN
SymbolInfoDouble
SYMBOL_VOLUME_STEP
SymbolInfoDouble
disabled
for the
4256
SymbolInfoInteger
SYMBOL_VOLUMELOW
SymbolInfoInteger
TENKANSEN_LINE
Tenkan-sen line
Indicators Lines
TERMINAL_BUILD
The client
number
build
TerminalInfoInteger
TERMINAL_CODEPAGE
TerminalInfoInteger
TERMINAL_COMMONDATA_PA
TH
TerminalInfoString
TERMINAL_COMMUNITY_ACCO
UNT
The
flag
indicates
the
presence of MQL5.community
authorization data in the
terminal
TerminalInfoInteger
TERMINAL_COMMUNITY_BALA
NCE
Balance in MQL5.community
TerminalInfoDouble
TERMINAL_COMMUNITY_CONN
ECTION
Connection
MQL5.community
TERMINAL_COMPANY
Company name
TerminalInfoString
TERMINAL_CONNECTED
TerminalInfoInteger
TERMINAL_CPU_CORES
TerminalInfoInteger
TERMINAL_DATA_PATH
TerminalInfoString
TERMINAL_DISK_SPACE
TerminalInfoInteger
TERMINAL_DLLS_ALLOWED
TerminalInfoInteger
TERMINAL_EMAIL_ENABLED
TerminalInfoInteger
TERMINAL_FTP_ENABLED
TerminalInfoInteger
TERMINAL_LANGUAGE
TerminalInfoString
TERMINAL_MAXBARS
TerminalInfoInteger
terminal
to
TerminalInfoInteger
4257
chart
TERMINAL_MEMORY_AVAILABL
E
TerminalInfoInteger
TERMINAL_MEMORY_PHYSICAL
Physical memory
system, MB
in
the
TerminalInfoInteger
TERMINAL_MEMORY_TOTAL
Memory available
process of the
(agent), MB
to the
terminal
TerminalInfoInteger
TERMINAL_MEMORY_USED
TerminalInfoInteger
TERMINAL_MQID
The
flag
indicates
the
presence of MetaQuotes ID
data for Push notifications
TerminalInfoInteger
TERMINAL_NAME
Terminal name
TerminalInfoString
TERMINAL_NOTIFICATIONS_EN
ABLED
Permission
to
send
notifications to smartphone
TerminalInfoInteger
TERMINAL_OPENCL_SUPPORT
TerminalInfoInteger
TERMINAL_PATH
TerminalInfoString
TERMINAL_PING_LAST
TerminalInfoInteger
TERMINAL_SCREEN_DPI
TerminalInfoInteger
TERMINAL_TRADE_ALLOWED
Permission to trade
TerminalInfoInteger
TERMINAL_X64
Indication
terminal"
THURSDAY
Thursday
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
TRADE_ACTION_DEAL
MqlTradeRequest
of
the
"64-bit
TerminalInfoInteger
4258
TRADE_ACTION_MODIFY
MqlTradeRequest
TRADE_ACTION_PENDING
MqlTradeRequest
TRADE_ACTION_REMOVE
order
MqlTradeRequest
TRADE_ACTION_SLTP
MqlTradeRequest
TRADE_RETCODE_CANCEL
MqlTradeResult
TRADE_RETCODE_CLIENT_DIS
ABLES_AT
MqlTradeResult
TRADE_RETCODE_CONNECTIO
N
MqlTradeResult
TRADE_RETCODE_DONE
Request completed
MqlTradeResult
TRADE_RETCODE_DONE_PARTI
AL
MqlTradeResult
TRADE_RETCODE_ERROR
MqlTradeResult
TRADE_RETCODE_FROZEN
MqlTradeResult
TRADE_RETCODE_INVALID
Invalid request
MqlTradeResult
TRADE_RETCODE_INVALID_EXP
IRATION
MqlTradeResult
TRADE_RETCODE_INVALID_FIL
L
MqlTradeResult
TRADE_RETCODE_INVALID_OR
DER
MqlTradeResult
TRADE_RETCODE_INVALID_PRI
CE
MqlTradeResult
TRADE_RETCODE_INVALID_ST
OPS
MqlTradeResult
TRADE_RETCODE_INVALID_VO
LUME
MqlTradeResult
TRADE_RETCODE_LIMIT_ORDE
RS
MqlTradeResult
TRADE_RETCODE_LIMIT_VOLU
ME
MqlTradeResult
TRADE_RETCODE_LOCKED
MqlTradeResult
4259
TRADE_RETCODE_MARKET_CL
OSED
Market is closed
MqlTradeResult
TRADE_RETCODE_NO_CHANGE
S
No changes in request
MqlTradeResult
TRADE_RETCODE_NO_MONEY
MqlTradeResult
TRADE_RETCODE_ONLY_REAL
MqlTradeResult
TRADE_RETCODE_ORDER_CHA
NGED
MqlTradeResult
TRADE_RETCODE_PLACED
Order placed
MqlTradeResult
TRADE_RETCODE_POSITION_C
LOSED
MqlTradeResult
TRADE_RETCODE_PRICE_CHAN
GED
Prices changed
MqlTradeResult
TRADE_RETCODE_PRICE_OFF
MqlTradeResult
TRADE_RETCODE_REJECT
Request rejected
MqlTradeResult
TRADE_RETCODE_REQUOTE
Requote
MqlTradeResult
TRADE_RETCODE_SERVER_DIS
ABLES_AT
MqlTradeResult
TRADE_RETCODE_TIMEOUT
MqlTradeResult
TRADE_RETCODE_TOO_MANY_
REQUESTS
MqlTradeResult
TRADE_RETCODE_TRADE_DISA
BLED
Trade is disabled
MqlTradeResult
TRADE_TRANSACTION_DEAL_A
DD
MqlTradeTransaction
TRADE_TRANSACTION_DEAL_D
ELETE
MqlTradeTransaction
4260
TRADE_TRANSACTION_DEAL_U
PDATE
MqlTradeTransaction
TRADE_TRANSACTION_HISTOR
Y_ADD
MqlTradeTransaction
TRADE_TRANSACTION_HISTOR
Y_DELETE
MqlTradeTransaction
TRADE_TRANSACTION_HISTOR
Y_UPDATE
MqlTradeTransaction
TRADE_TRANSACTION_ORDER
_ADD
MqlTradeTransaction
TRADE_TRANSACTION_ORDER
_DELETE
MqlTradeTransaction
TRADE_TRANSACTION_ORDER
_UPDATE
MqlTradeTransaction
TRADE_TRANSACTION_POSITI
ON
MqlTradeTransaction
4261
MqlTradeTransaction
TUESDAY
Tuesday
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
TYPE_BOOL
bool
MqlParam
TYPE_CHAR
char
MqlParam
TYPE_COLOR
color
MqlParam
TYPE_DATETIME
datetime
MqlParam
TYPE_DOUBLE
double
MqlParam
TYPE_FLOAT
float
MqlParam
TYPE_INT
int
MqlParam
TYPE_LONG
long
MqlParam
TYPE_SHORT
short
MqlParam
TYPE_STRING
string
MqlParam
4262
TYPE_UCHAR
uchar
MqlParam
TYPE_UINT
uint
MqlParam
TYPE_ULONG
ulong
MqlParam
TYPE_USHORT
ushort
MqlParam
UCHAR_MAX
UINT_MAX
ULONG_MAX
UPPER_BAND
Upper limit
Indicators Lines
UPPER_HISTOGRAM
Upper histogram
Indicators Lines
UPPER_LINE
Upper line
Indicators Lines
USHORT_MAX
VOLUME_REAL
Trade volume
Price Constants
VOLUME_TICK
Tick volume
Price Constants
WEDNESDAY
Wednesday
SymbolInfoInteger,
SymbolInfoSessionQuote,
SymbolInfoSessionTrade
WHOLE_ARRAY
Other Constants
WRONG_VALUE
Other Constants