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