0% found this document useful (0 votes)
833 views4,262 pages

MQL 5

asd

Uploaded by

Kalev Lillemets
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
833 views4,262 pages

MQL 5

asd

Uploaded by

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

MQL5 Language REFERENCE

for the MetaTrader 5 client terminal

STUDY MQL5 and


SOLVE any tasks:
your own technical analysis indicators
Create
of any complexity
autotrading - automate trading systems
Use
to work on various financial markets
your own analytical tools based on
Develop
mathematical achievements and traditional
methods
information trading systems for solving
Write
a wide range of tasks (trading, monitoring,
alerting, etc.)

2000-2016, MetaQuotes Software Corp.

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

Date and Time


................................................................................................. 1012
............................................................................................................................1013
TimeCurrent
............................................................................................................................1014
TimeTradeServer
TimeLocal............................................................................................................................1015
TimeGMT ............................................................................................................................1016
............................................................................................................................1017
TimeDay lightSavings
............................................................................................................................1018
TimeGMTOffset
............................................................................................................................1019
TimeToStruct
............................................................................................................................1020
StructToTime

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

Market Info ................................................................................................. 1039


............................................................................................................................1040
Sy mbolsTotal
............................................................................................................................1041
Sy mbolName
............................................................................................................................1042
Sy mbolSelect
............................................................................................................................1043
Sy mbolIsSy
nchronized
............................................................................................................................1044
Sy mbolInfoDouble
............................................................................................................................1046
Sy mbolInfoInteger
............................................................................................................................1048
Sy mbolInfoString
............................................................................................................................1049
Sy mbolInfoMarginRate
............................................................................................................................1050
Sy mbolInfoTick
............................................................................................................................1051
Sy mbolInfoSessionQuote
............................................................................................................................1052
Sy mbolInfoSessionTrade
............................................................................................................................1053
MarketBookAdd
............................................................................................................................1054
MarketBookRelease
............................................................................................................................1055
MarketBookGet

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

Trade Signals................................................................................................. 1235


............................................................................................................................1236
SignalBaseGetDouble
............................................................................................................................1237
SignalBaseGetInteger
............................................................................................................................1238
SignalBaseGetString
............................................................................................................................1239
SignalBaseSelect
............................................................................................................................1240
SignalBaseTotal
............................................................................................................................1241
SignalInfoGetDouble
............................................................................................................................1242
SignalInfoGetInteger
............................................................................................................................1243
SignalInfoGetString
............................................................................................................................1244
SignalInfoSetDouble
............................................................................................................................1245
SignalInfoSetInteger
............................................................................................................................1246
SignalSubscribe
2000-2016, MetaQuotes Software Corp.

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

Moving from .................................................................................................


MQL4
4168

28

List of MQL5 .................................................................................................


Functions
4171

29

List of MQL5 .................................................................................................


Constants
4196

2000-2016, MetaQuotes Software Corp.

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.

Types of MQL5 Applications


MQL5 programs are divided into four specialized types based on the trading automation tasks that
they implement:
Expert Advisor is an automated trading system linked to a chart. An Expert Advisor contains event

handlers to manage predefined events which activate execution of appropriate trading strategy
elements. For example, an event of program initialization and deinitializtion, new ticks, timer
events, changes in the Depth of Market, chart and custom events.
In addition to calculating trading signals based on the implemented rules, Expert Advisors can also
automatically execute trades and send them directly to a trading server. Expert Advisors are stored
in <Terminal_Directory>\MQL5\Experts.
Custom 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

algorithms of custom programs.


Libraries are stored in <Terminal_Directory>\MQL5\Libraries.
Include File is a source text of the most frequently used blocks of custom programs. Such files can

be included into the source texts of Expert Advisors, scripts, custom indicators, and libraries at the
compiling stage. The use of included files is more preferable than the use of libraries because of
additional burden occurring at calling library functions.
Include files can be stored in the same directory 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.

2000-2016, MetaQuotes Software Corp.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

// Nested single-line comment

comment
*/

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

58

Language Basics

2000-2016, MetaQuotes Software Corp.

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

Complex data types are:


structures;
classes.

In terms of OOP complex data types are called abstract data types.
The color and datetime types make sense only to facilitate visualization and input of parameters
defined from outside - from the table of Expert Advisor or custom indicator properties (the Inputs
tab). Data of color and datetime types are represented as integers. Integer types and floating-point
types are called arithmetic (numeric) types.
Only implicit type casting is used in expressions, unless the explicit casting is specified.
See also
Typecasting

2000-2016, MetaQuotes Software Corp.

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

- 2 147 483 648

2 147 483 647

int

uint

4 294 967 295

unsigned
DWORD

color

-1

16 777 215

int, COLORREF

long

-9 223 372 036


854 775 808

9 223 372 036


854 775 807

__int64

ulong

18 446 744 073


709 551 615

unsigned __int64

datetime

0
(1970.01.01
0:00:00)

32 535 244 799


(3000.12.31
23:59:59)

__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

2000-2016, MetaQuotes Software Corp.

61

Language Basics

Char, Short, Int and Long Types


char
The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256
values. The char type can contain both positive and negative values. The range of values is from -128
to 127.

uchar
The uchar integer type also occupies 1 byte of memory, as well as the char type, but unlike it uchar is
intended only for positive values. The minimum value is zero, the maximum value is 255. The first
letter u in the name of the uchar type is the abbreviation for unsigned.

short
The size of the short type is 2 bytes (16 bits) and, accordingly, it allows expressing the range of values
equal to 2 to the power 16: 2^16 = 65 536.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;

2000-2016, MetaQuotes Software Corp.

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

The correct variant is:


//--- Correct variant
void OnStart()
{
uchar

u_ch;

for(char ch=-128;ch<=127;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
if(ch==127) break;
}
}

Result:
ch= -128

u_ch= 128

ch= -127

u_ch= 129

ch= -126

u_ch= 130

ch= -125

u_ch= 131

ch= -124

u_ch= 132

ch= -123

u_ch= 133

ch= -122

u_ch= 134

ch= -121

u_ch= 135

ch= -120

u_ch= 136

ch= -119

u_ch= 137

ch= -118

u_ch= 138

ch= -117

u_ch= 139

ch= -116

u_ch= 140

ch= -115

u_ch= 141

ch= -114

u_ch= 142

ch= -113

u_ch= 143

ch= -112

u_ch= 144

ch= -111

u_ch= 145

2000-2016, MetaQuotes Software Corp.

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

=B'111111111'; // Asian session from 0:00 to 9:00

int EuropeanSession=B'111111111000000000'; // European session 9:00 - 18:00


int AmericanSession =B'111111110000000000000011'; // American session 16:00 - 02:00
//--- derive numerical values of the sessions
PrintFormat("Asian session hours as value =%d",AsianSession);
PrintFormat("European session hours as value is %d",EuropeanSession);
PrintFormat("American session hours as value is %d",AmericanSession);
//--- and now let's display string representations of the sessions' working hours
Print("Asian session ",GetHoursForSession(AsianSession));
Print("European session ",GetHoursForSession(EuropeanSession));
Print("American session ",GetHoursForSession(AmericanSession));
//--}
//+------------------------------------------------------------------+
//| return the session's working hours as a string

//+------------------------------------------------------------------+
string GetHoursForSession(int session)
{
//--- in order to check, use AND bit operations and left shift by 1 bit <<=1
//--- start checking from the lowest bit
int bit=1;
string out="working hours: ";
//--- check all 24 bits starting from the zero and up to 23 inclusively
for(int i=0;i<24;i++)
{
//--- receive bit state in number

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

printf("In a hexadecimal form: symbol_0 = 0x%x,

symbol_9 = 0x%x",symbol_0,symbol_9);

//--- enter constants into a string


string test="";
StringSetCharacter(test,0,symbol_0);
StringSetCharacter(test,1,symbol_9);
//--- this is what they look like in a string
Print(test);
}

A backslash is a control character for a compiler when dealing with constant strings and character
constants in a source text of a program. Some symbols, for example a single quote ('), double quotes
("), backslash (\) and control characters can be represented as a combination of symbols that start
with a backslash (\), according to the below table:
Character name

Mnemonic code or
image

Record in MQL5

Numeric value

new line (line feed)

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'

decimal number from


0 to 65535

2000-2016, MetaQuotes Software Corp.

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

// code of the symbol

//--- output print constants


Print(a,b,c,d);
//--- add a character to the string
string test="";
StringSetCharacter(test,0,a);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,b);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,c);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,d);
Print(test);
//--- represent characters as a number
int a1=65;
int b1=36;
int c1=169;
int d1=174;
//--- add a character to the string
StringSetCharacter(test,1,a1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,b1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,c1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,d1);
Print(test);
}

As it was mentioned above, the value of a character constant (or variable) is an index in the table of
characters. Index being an integer, it can be written in different ways.
void OnStart()
{

2000-2016, MetaQuotes Software Corp.

67

Language Basics
//--int a=0xAE;

// the code of corresponds to the '\xAE' literal

int b=0x24;

// the code of $ corresponds to the '\x24' literal

int c=0xA9;

// the code of corresponds to the '\xA9' literal

int d=0x263A;

// the code of corresponds to the '\x263A' literal

//--- show values


Print(a,b,c,d);
//--- add a character to the string
string test="";
StringSetCharacter(test,0,a);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,b);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,c);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,d);
Print(test);
//--- codes of suits
int a1=0x2660;
int b1=0x2661;
int c1=0x2662;
int d1=0x2663;
//--- add a character of spades
StringSetCharacter(test,1,a1);
Print(test);
//--- add a character of hearts
StringSetCharacter(test,2,b1);
Print(test);
//--- add a character of diamonds
StringSetCharacter(test,3,c1);
Print(test);
//--- add a character of clubs
StringSetCharacter(test,4,d1);
Print(test);
//--- Example of character literals in a string
test="Queen\x2660Ace\x2662";
printf("%s",test);
}

The internal representation of a character literal is the ushort type. Character constants can accept
values from 0 to 65535.
See also
StringSetCharacter(), StringGetCharacter(), ShortToString(), ShortArrayToString(),
StringToShortArray()

2000-2016, MetaQuotes Software Corp.

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

// Time of beginning of year 2015

datetime d1=D'1980.07.19 12:30:27';

// Year Month Day Hours Minutes Seconds

datetime d2=D'19.07.1980 12:30:27';

// Equal to D'1980.07.19 12:30:27';

datetime d3=D'19.07.1980 12';

// Equal to D'1980.07.19 12:00:00'

datetime d4=D'01.01.2004';

// Equal to D'01.01.2004 00:00:00'

datetime compilation_date=__DATE__;

// Compilation date

datetime compilation_date_time=__DATETIME__;

// Compilation date and time

datetime compilation_time=__DATETIME__-__DATE__;// Compilation time


//--- Examples of declarations after which compiler warnings will be returned
datetime warning1=D'12:30:27';

// Equal to D'[date of compilation] 12:30:27'

datetime warning2=D'';

// Equal to __DATETIME__

See also
Structure of the Date Type, Date and Time, TimeToString, StringToTime

2000-2016, MetaQuotes Software Corp.

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

//--- Integral representations


0xFFFFFF

// White

16777215

// White

0x008000

// Green

32768

// Green

See also
Web Colors, ColorToString, StringToColor, Typecasting

2000-2016, MetaQuotes Software Corp.

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

i= 5 and has the true value

//

d= -2.5 and has the true value

//

i= 0 and has the false value

//

d= 0 and has the false value

See also
Boolean Operations, Precedence Rules

2000-2016, MetaQuotes Software Corp.

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

The list of values is a list of identifiers of named constants separated by commas.


Example:
enum months

// enumeration of named constants

{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};

After the enumeration is declared, a new integer-valued 4-byte data type appears. Declaration of the
new data type allows the compiler to strictly control types of passed parameters, because enumeration
introduces new named constants. In the above example, the January named constant has the value of
0, February - 1, December - 11.
Rule: If a certain value is not assigned to a named constant that is a member of the enumeration, its
new value will be formed automatically. If it is the first member of the enumeration, the 0 value will
be assigned to it. For all subsequent members, values will be calculated based on the value of the
previous members by adding one.
Example:
enum intervals

// Enumeration of named constants

{
month=1,

// Interval of one month

two_months,

// Two months

quarter,

// Three months - quarter

halfyear=6,

// Half a year

year=12,

// Year - 12 months

};

Notes

2000-2016, MetaQuotes Software Corp.

72

Language Basics
Unlike C++, the size of the internal representation of the enumerated type in MQL5 is always equal

to 4 bytes. That is, sizeof (months) returns the value 4.


Unlike C++, an anonymous enumeration can't be declared in MQL5. That is, a unique name must be

always specified after the enum keyword.


See also
Typecasting

2000-2016, MetaQuotes Software Corp.

73

Language Basics

Real Types (double, float)


Real types (or floating-point types) represent values with a fractional part. In the MQL5 language there
are two types for floating point numbers.The method of representation of real numbers in the
computer memory is defined by the IEEE 754 standard and is independent of platforms, operating
systems or programming languages.
Type

Size in bytes

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

2000-2016, MetaQuotes Software Corp.

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;

if(EqualDoubles(d_val,f_val,0.000000000000001)) Print(d_val," equals ",f_val);


else Print("Different: d_val = ",DoubleToString(d_val,16),
"

f_val = ",DoubleToString(f_val,16));

// Result: Different: d_val= 0.7000000000000000

f_val= 0.6999999880790710

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

2000-2016, MetaQuotes Software Corp.

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;

if(CompareDoubles(d_val,f_val)) Print(d_val," equals ",f_val);


else Print("Different: d_val = ",DoubleToString(d_val,16),
"

f_val = ",DoubleToString(f_val,16));

// Result: Different: d_val= 0.3000000000000000

f_val= 0.3000000119209290

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;

2000-2016, MetaQuotes Software Corp.

76

Language Basics
//--s1.d=MathArcsin(2.0);

// Get the invalid number -1.#IND

s2=s1;
printf("1.

%f %I64X",s1.d,s2.l);

//--s2.l=0xFFFF000000000000;

// invalid number -1.#QNAN

s1=s2;
printf("2.

%f %I64X",s1.d,s2.l);

//--s2.l=0x7FF7000000000000;

// greatest non-number SNaN

s1=s2;
printf("3.

%f %I64X",s1.d,s2.l);

//--s2.l=0x7FF8000000000000;

// smallest non-number QNaN

s1=s2;
printf("4.

%f %I64X",s1.d,s2.l);

//--s2.l=0x7FFF000000000000;

// greatest non-number QNaN

s1=s2;
printf("5.

%f %I64X",s1.d,s2.l);

//--s2.l=0x7FF0000000000000;

// Positive infinity 1.#INF and smallest non-number SNaN

s1=s2;
printf("6.

%f %I64X",s1.d,s2.l);

//--s2.l=0xFFF0000000000000;

// Negative infinity -1.#INF

s1=s2;
printf("7.

%f %I64X",s1.d,s2.l);

//--s2.l=0x8000000000000000;

// Negative zero -0.0

s1=s2;
printf("8.

%f %I64X",s1.d,s2.l);

//--s2.l=0x3FE0000000000000;

// 0.5

s1=s2;
printf("9.

%f %I64X",s1.d,s2.l);

//--s2.l=0x3FF0000000000000;

// 1.0

s1=s2;
printf("10.

%f %I64X",s1.d,s2.l);

//--s2.l=0x7FEFFFFFFFFFFFFF;

// Greatest normalized number (MAX_DBL)

s1=s2;
printf("11.

%.16e %I64X",s1.d,s2.l);

//--s2.l=0x0010000000000000;

// Smallest positive normalized (MIN_DBL)

s1=s2;
printf("12.

%.16e %.16I64X",s1.d,s2.l);

//---

2000-2016, MetaQuotes Software Corp.

77

Language Basics
s1.d=0.7;

// Show that the number of 0.7 - endless fraction

s2=s1;
printf("13.

%.16e %.16I64X",s1.d,s2.l);

/*
1.

-1.#IND00 FFF8000000000000

2.

-1.#QNAN0 FFFF000000000000

3.

1.#SNAN0 7FF7000000000000

4.

1.#QNAN0 7FF8000000000000

5.

1.#QNAN0 7FFF000000000000

6.

1.#INF00 7FF0000000000000

7.

-1.#INF00 FFF0000000000000

8.

-0.000000 8000000000000000

9.

0.500000 3FE0000000000000

10.

1.000000 3FF0000000000000

11.

1.7976931348623157e+308 7FEFFFFFFFFFFFFF

12.

2.2250738585072014e-308 0010000000000000

13.

6.9999999999999996e-001 3FE6666666666666

*/

See also
DoubleToString, NormalizeDouble, Numeric Type Constants

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

79

Language Basics

Structures and Classes


Structures
A structure is a set of elements of any type (except for the void type). Thus, the structure combines
logically related data of different types.

Structure Declaration
The structure data type is determined by the following description:
struct structure_name
{
elements_description
};

The structure name can't be used as an identifier (name of a variable or function). It should be noted
that in MQL5 structure elements follow one another directly, without alignment. In C++ such an order
is made to the compiler using the following instruction:
#pragma pack(1)

If you want to do another alignment in the structure, use auxiliary members, "fillers" to the right size.
Example:
struct trade_settings
{
uchar

slippage;

// value of the permissible slippage-size 1 byte

char

reserved1;

// skip 1 byte

short

reserved2;

// skip 2 bytes

int

reserved4;

// another 4 bytes are skipped. ensure alignment of the boundary 8 bytes

double take;

// values of the price of profit fixing

double stop;

// price value of the protective stop

};

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

2000-2016, MetaQuotes Software Corp.

80

Language Basics
imported from DLL.

Access to Structure Members


The name of a structure becomes a new data type, so you can declare variables of this type. The
structure can be declared only once within a project. The structure members are accessed using the
point operation (.).
Example:
struct trade_settings
{
double take;

// values of the profit fixing price

double stop;

// value of the protective stop price

uchar

// value of the acceptable slippage

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

in the class. Structures can't have virtual functions;


the new operator can be applied to class objects; this operator cannot be applied to structures;
classes can be inherited only from classes, structures can be inherited only from structures.

Classes and structures can have an explicit constructor and destructor. If your constructor is explicitly
defined, the initialization of a structure or class variable using the initializing sequence is impossible.
Example:
struct trade_settings
{
double take;

// values of the profit fixing price

double stop;

// value of the protective stop price

uchar

// value of the acceptable slippage

slippage;

//--- Constructor
trade_settings() { take=0.0; stop=0.0; slippage=5; }
//--- Destructor
~trade_settings() { Print("This is the end"); }
};
//--- Compiler will generate an error message that initialization is impossible
trade_settings my_set={0.0,0.0,5};

2000-2016, MetaQuotes Software Corp.

81

Language Basics

Constructors and Destructors


A constructor is a special function, which is called automatically when creating an object of a structure
or class and is usually used to initialize class members. Further we will talk only about classes, while
the same applies to structures, unless otherwise indicated. The name of a constructor must match the
class name. The constructor has no return type (you can specify the void type).
Defined class members strings, dynamic arrays and objects that require initialization will be in any
case initialized, regardless of whether there is a constructor.
Each class can have multiple constructors, differing by the number of parameters and the initialization
list. A constructor that requires specifying parameters is called a parametric constructor.
A constructor with no parameters is called a default constructor. If no constructors are declared in a
class, the compiler creates a default constructor during compilation.
//+------------------------------------------------------------------+
//| A class for working with a date

//+------------------------------------------------------------------+
class MyDateClass
{
private:
int

m_year;

// Year

int

m_month;

// Month

int

m_day;

// Day of the month

int

m_hour;

// Hour in a day

int

m_minute;

// Minutes

int

m_second;

// Seconds

public:
//--- Default constructor
MyDateClass(void);
//--- Parametric constructor
MyDateClass(int h,int m,int s);
};

A constructor can be declared in the class description and then its body can be defined. For example,
two constructors of MyDateClass can be defined the following way:
//+------------------------------------------------------------------+
//| Default constructor

//+------------------------------------------------------------------+
MyDateClass::MyDateClass(void)
{
//--MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;

2000-2016, MetaQuotes Software Corp.

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;

// Time of the last object call

public:
//--- Constructor with a parameter that has a default value is not a default constructor
CFoo(const datetime t=0){m_call_time=t;};
//--- Copy constructor
CFoo(const CFoo &foo){m_call_time=foo.m_call_time;};
string ToString(){return(TimeToString(m_call_time,TIME_DATE|TIME_SECONDS));};
};
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
// CFoo foo; // This variant cannot be used - a default constructor is not set
//--- Possible options to create the CFoo object

2000-2016, MetaQuotes Software Corp.

83

Language Basics
CFoo foo1(TimeCurrent());

// An explicit call of a parametric constructor

CFoo foo2();

// An explicit call of a parametric constructor with a default par

CFoo foo3=D'2009.09.09';

// An implicit call of a parametric constructor

CFoo foo40(foo1);

// An explicit call of a copy constructor

CFoo foo41=foo1;

// An implicit call of a copy constructor

CFoo foo5;

// An explicit call of a default constructor (if there is no defau


// then a parametric constructor with a default value is called)

//--- Possible options to receive CFoo pointers


CFoo *pfoo6=new CFoo();

// Dynamic creation of an object and receiving of a pointer to it

CFoo *pfoo7=new CFoo(TimeCurrent());// Another option of dynamic object creation


CFoo *pfoo8=GetPointer(foo1); // Now pfoo8 points to object foo1
CFoo *pfoo9=pfoo7;

// pfoo9 and pfoo7 point to one and the same object

// CFoo foo_array[3];

// This option cannot be used - a default constructor is not speci

//--- Show the value of m_call_time


Print("foo1.m_call_time=",foo1.ToString());
Print("foo2.m_call_time=",foo2.ToString());
Print("foo3.m_call_time=",foo3.ToString());
Print("foo4.m_call_time=",foo4.ToString());
Print("foo5.m_call_time=",foo5.ToString());
Print("pfoo6.m_call_time=",pfoo6.ToString());
Print("pfoo7.m_call_time=",pfoo7.ToString());
Print("pfoo8.m_call_time=",pfoo8.ToString());
Print("pfoo9.m_call_time=",pfoo9.ToString());
//--- Delete dynamically created arrays
delete pfoo6;
delete pfoo7;
//delete pfoo8;

// You do not need to delete pfoo8 explicitly, since it points to the automatic

//delete pfoo9;

// You do not need to delete pfoo9 explicitly. since it points to the same obje

If you uncomment these strings


//CFoo foo_array[3];

// This variant cannot be used - a default constructor is not set

or
//CFoo foo_dyn_array[];

// This variant cannot be used - a default constructor is not set

then the compiler will return an error for them "default constructor is not defined".
If a class has a user-defined constructor, the default constructor is not generated by the compiler. This
means that if a parametric constructor is declared in a class, but a default constructor is not declared,
you can not declare the arrays of objects of this class. The compiler will return an error for this script:
//+------------------------------------------------------------------+
//| A class without a default constructor

//+------------------------------------------------------------------+
class CFoo
{
string

m_name;

public:

2000-2016, MetaQuotes Software Corp.

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.

Here is an example of several constructors for initializing class members.


//+------------------------------------------------------------------+
//| A class for storing the name of a character

//+------------------------------------------------------------------+
class CPerson
{
string

m_first_name;

// First name

string

m_second_name;

// Second name

public:
//--- An empty default constructor
CPerson() {Print(__FUNCTION__);};
//--- A parametric constructor
CPerson(string full_name);
//--- A constructor with an initialization list

CPerson(string surname,string name): m_second_name(surname), m_first_name(name


void PrintName(){PrintFormat("Name=%s Surname=%s",m_first_name,m_second_name);};
};
//+------------------------------------------------------------------+
//|

2000-2016, MetaQuotes Software Corp.

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

CPerson *Pooh = new CPerson("Winnie","Pooh");

// Winnie the Pooh

//--- Output values


Tom.PrintName();
Huck.PrintName();
Pooh.PrintName();
//--- Delete a dynamically created object
delete Pooh;
}

In this case, the CPerson class has three constructors:


1. An explicit default constructor, which allows creating an array of objects of this class;
2. A constructor with one parameter, which gets a full name as a parameter and divides it to the
name and second name according to the found space;
3. A constructor with two parameters that contains
m_second_name(surname) and m_first_name(name).

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

2000-2016, MetaQuotes Software Corp.

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;

// A class member is an object of the parent

public:
//--- A default constructor in the initialization list calls the constructor of a parent
CBar(): m_member(_Symbol), CFoo("CBAR") {Print(__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
CBar bar;
}

In this example, when creating the bar object, a default constructor CBar() will be called, in which first
a constructor for the parent CFoo is called, and then comes a constructor for the m_member class
member.
A destructor is a special function that is called automatically when a class object is destroyed. The
name of the destructor is written as a class name with a tilde (~). 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.

Defining Class Methods


Class function-methods can be defined both inside the class and outside the class declaration. If the
method is defined within a class, then its body comes right after the method declaration.
Example:
class CTetrisShape
{
protected:

2000-2016, MetaQuotes Software Corp.

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

SetRightBorder(int border) { m_right_border=border; }

void

SetYPos(int ypos)

{ m_ypos=ypos;

void

SetXPos(int xpos)

{ m_xpos=xpos;

int

GetYPos()

{ return(m_ypos);

int

GetXPos()

{ return(m_xpos);

int

GetYSize()

{ return(m_ysize);

int

GetXSize()

{ return(m_xsize);

int

GetType()

{ return(m_type);

void

Left()

{ m_xpos-=SHAPE_SIZE;

void

Right()

{ m_xpos+=SHAPE_SIZE;

void

Rotate()

{ m_prev_turn=m_turn; if(++m_turn>3) m_turn=0; }

virtual void

Draw()

{ return;

virtual bool

CheckDown(int& pad_array[]);

virtual bool

CheckLeft(int& side_row[]);

virtual bool

CheckRight(int& side_row[]);

};

Functions from 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;

2000-2016, MetaQuotes Software Corp.

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

Public, Protected and Private Access Modifiers


When developing a new class, it is recommended to restrict access to the members from the outside.
For this purpose keywords private or protected are used. In this case, hidden data can be accessed
only from function-methods of the same class. If the protected keyword is used, hidden data can be
accessed also from methods of classes - inheritors of this class. The same method can be used to
restrict the access to functions-methods of a class.
If you need to completely open access to members and/or methods of a class, use the keyword public.
Example:
class CTetrisField
{
private:
int

m_score;

// Score

int

m_ypos;

// Current position of the figures

int

m_field[FIELD_HEIGHT][FIELD_WIDTH]; // Matrix of the well

int

m_rows[FIELD_HEIGHT];

// Numbering of the well rows

int

m_last_row;

// Last free row

CTetrisShape
bool

*m_shape;
m_bover;

// Tetris figure
// Game over

public:
void

CTetrisField() { m_shape=NULL; m_bover=false; }

void

Init();

void

Deinit();

void

Down();

void

Left();

void

Right();

void

Rotate();

void

Drop();

private:
void

NewShape();

void

CheckAndDeleteRows();

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

90

Language Basics

Dynamic Array Object


Dynamic Arrays
Maximum 4-dimension array can be declared. When declaring a dynamic array (an array of unspecified
value in the first pair of square brackets), the compiler automatically creates a variable of the above
structure (a dynamic array object) and provides a code for the correct initialization.
Dynamic arrays are automatically freed when going beyond the visibility area of the block they are
declared in.
Example:
double matrix[][10][20]; // 3-dimensional dynamic array
ArrayResize(matrix,5);

// Set the size of the first dimension

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

2000-2016, MetaQuotes Software Corp.

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;

// the content of f is equal to 1.234567892E8

Print("n = ",n,"

f = ",f);

// result n= 123456789

f= 123456792.00000

A number converted into float has the same order, but is less accurate. Conversions, contrary to black
arrows, can be performed with possible data loss. Conversions between char and uchar, short and
ushort, int and uint, long and ulong (conversions to both sides), may lead to the loss of data.
As a result of converting floating point values to integer type, the fractional part is always deleted. If
you want to round off a float to the nearest whole number (which in many cases is more useful), you
should use MathRound().
Example:
//--- Gravitational acceleration
double g=9.8;
double round_g=(int)g;
double math_round_g=MathRound(g);
Print("round_g = ",round_g);
Print("math_round_g = ",math_round_g);
/*
Result:
round_g = 9
math_round_g = 10
*/

2000-2016, MetaQuotes Software Corp.

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;

//--- First example


double d2=c1/2+0.3;
Print("c1/2 + 0.3 = ",d2);
// Result:

c1/2+0.3 = 1.3

//--- Second example


d2=c1/2.0+0.3;
Print("c1/2.0 + 0.3 = ",d2);
// Result:

c1/2.0+0.3 = 1.8

The calculated expression consists of two operations. In the first example, the variable c1 of the char
type is converted to a temporary variable of the int type, because the second operand in the division
operation, the constant 2, is of the higher type int. As a result of the integer division 3/2 we get the
value 1, which is of the int type.
In the second operation of the first example, the second operand is the constant 0.3, which is of the
double type, so the result of the first operation is converted into a temporary variable of the double
type with a value of 1.0.
In the second example the variable of the char type c1 is converted to a temporary variable of the
double type, because the second operand in the division operation, the constant 2.0, is of the double
type; no further conversions are made.

Typecasting of Numeric Types


In the expressions of the MQL5 language both explicit and implicit typecasting can be used. The
explicit typecasting is written as follows:
var_1 = (type)var_2;

An expression or function execution result can be used as the var_2 variable. The function style
notation of the explicit typecasting is also possible:
var_1 = type(var_2);

Let's consider an explicit typecasting on the basis of the first example.


//--- Third example
double d2=(double)c1/2+0.3;

2000-2016, MetaQuotes Software Corp.

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

// no types casting, the result is 0


",i);

int k=1/2.0;
Print("k = 1/2

// the expression is cast to the double type,


",k);

double d=1.0/2.0;

// then is to the target type of int, the result is 0

// no types casting, the result is 0.5

Print("d = 1/2.0; ",d);


double e=1/2.0;

// the expression is cast to the double type,

Print("e = 1/2.0; ",e);// that is the same as the target type, the result is 0.5
double x=1/2;

// the expression of the int type is cast to the double target typr,

Print("x = 1/2; ",x);

// the result is 0.0

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

2000-2016, MetaQuotes Software Corp.

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

// When casting an integer value to double, it should be within [-9223372036854774784, 922337203685

// l_max+1=9223372036854774785, double(l_max+1)=9223372036854774800, ulong(double(l_max+1))=9223372

// l_min-1=-9223372036854774785, double(l_min-1)=-9223372036854774800, ulong(double(l_min-1))=-9223


}

Typecasting for the String Type


The string type has the highest priority among simple types. Therefore, if one of operands of an
operation is of the string type, the second operand will be cast to a string automatically. Note that for
a string, a single dyadic two-place operation of addition is possible. The explicit casting of string to
any numeric type is allowed.
Examples:
string s1=1.0/8;

// the expression is cast to the double type,

Print("s1 = 1.0/8; ",s1);

//

then is to the target type of string,

// result is "0.12500000" (a string containing 10 characters)


string s2=NULL;

// string deinitialization

Print("s2 = NULL; ",s2);

// the result is an empty string

string s3="Ticket N"+12345; // the expression is cast to the string type


Print("s3 = \"Ticket N\"+12345",s3);
string str1="true";
string str2="0,255,0";
string str3="2009.06.01";
string str4="1.2345e2";
Print(bool(str1));
Print(color(str2));
Print(datetime(str3));
Print(double(str4));

Typecasting of Simple Structure Types


Data of the simple structures type can be assigned to each other only if all the members of both
structures are of numeric types. In this case both operands of the assignment operation (left and
right) must be of the structures type. The member-wise casting is not performed, a simple copying is
done. If the structures are of different sizes, the number of bytes of the smaller size is copied. Thus

2000-2016, MetaQuotes Software Corp.

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

// get the invalid number -1. # IND

s2=s1;
printf("1.

%f

%I64X",s1.d,s2.l);

//--s3=s2;
printf("2.

high part of long %.8X

low part of long %.8X",

s3.high_part,s3.low_part);
//--s4.s="some constant string";
s3=s4;
printf("3.

buffer len is %d

constant string address is 0x%.8X",

s3.low_part,s3.high_part);
}

Another example illustrates the method of organizing a custom function for receiving RGB (Red,
Green, Blue) representation from the color type. Create two structures of the same size but with
different contents. For convenience, let's add a function returning the RGB representation of a color as

2000-2016, MetaQuotes Software Corp.

96

Language Basics
a string.
#property script_show_inputs
input color

testColor=clrBlue;// set color for testing

//--- structure for representing color as RGB


struct RGB
{
uchar

blue;

// blue component of color

uchar

green;

// green component of color

uchar

red;

// red component of color

uchar

empty;

// this byte is not used

string

toString();

// function for receiving a string

};
//--- function for showing color as a string
string RGB::toString(void)
{
string out="("+(string)red+":"+(string)green+":"+(string)blue+")";
return out;
}
//--- structure for storing of the built-in color type
struct builtColor
{
color

c;

};
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- a variable for storing in RGB
RGB colorRGB;
//--- variable for storing the color type
builtColor test;
test.c=testColor;
//--- casting two structures by copying contents
colorRGB=test;
Print("color ",test.c,"=",colorRGB.toString());
//--}

Typecasting of Base Class Pointers to Pointers of Derivative Classes


Objects of the open generated class can also be viewed as objects of the corresponding base class.
This leads to some interesting consequences. For example, despite the fact that objects of different
classes, generated by a single base class, may differ significantly from each other, we can create a
linked list (List) of them, as we view them as objects of the base type. But the converse is not true:
the base class objects are not automatically objects of a derived class.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

98

Language Basics

Void Type and NULL Constant


Syntactically the void type is a fundamental type along with types of char, uchar, bool, short, ushort,
int, uint, color, long, ulong, datetime, float, double and string. This type is used either to indicate
that the function does not return any value, or as a function parameter it denotes the absence of
parameters.
The predefined constant variable NULL is of the void type. It can be assigned to variables of any other
fundamental types without conversion. The comparison of fundamental type variables with the NULL
value is allowed.
Example:
//--- If the string is not initialized, then assign our predefined value to it
if(some_string==NULL) some_string="empty";

Also NULL can be compared to pointers to objects created with the new operator.
See also
Variables, Functions

2000-2016, MetaQuotes Software Corp.

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;

//--- constructors and desctructors


Foo(void){Setup("noname");};
Foo(string name){Setup(name);};
~Foo(void){};
//--- initializes object of type Foo
void

Setup(string name)

{
m_name=name;
s_counter++;
m_id=s_counter;
}
};
int Foo::s_counter=0;
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- declare an object as variable with its automatic creation
Foo foo1;
//--- variant of passing an object by reference
PrintObject(foo1);
//--- declare a pointer to an object and create it using the 'new' operator
Foo *foo2=new Foo("foo2");
//--- variant of passing a pointer to an object by reference
PrintObject(foo2); // pointer to an object is converted automatically by compiler
//--- declare an array of objects of type Foo
Foo foo_objects[5];

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

101

Language Basics
//+------------------------------------------------------------------+

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

2000-2016, MetaQuotes Software Corp.

102

Language Basics

References: Modifier & and Keyword this


Passing Parameters by Reference
In MQL5 parameters of simple types can be passed both by value and by reference, while parameters
of compound types are always passed by reference. To inform the compiler that a parameter must be
passed by reference, the ampersand character & is added before the parameter name.
Passing a parameter by reference means passing the address of the variable, that's why all changes in
the parameter that is passed by reference will be immediately reflected in the source variable. Using
parameter passing by reference, you can implement return of several results of a function at the same
time. In order to prevent changing of a parameter passed by reference, use the const modifier.
Thus, if the input parameter of a function is an array, a structure or class object, symbol '&' is placed
in the function header after the variable type and before its name.
Example
class CDemoClass
{
private:
double

m_array[];

public:
void

setArray(double &array[]);

};
//+------------------------------------------------------------------+
//| filling the array

//+------------------------------------------------------------------+
void

CDemoClass::setArray(double &array[])

{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array, array);
}
}

In the above example class CDemoClass is declared, which contains the private member - array
m_array[] of double type. Function setArray() is declared, to which array[] is passed by reference. If
the function header doesn't contain the indication about passing by reference, i.e. doesn't contain the
ampersand character, an error message will be generated at the attempt to compile such a code.
Despite the fact that the array is passed by reference, we can't assign one array to another. 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,

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

104

Language Basics

Operations and Expressions


Some characters and character sequences are of a special importance. These are so-called operation
symbols, for example:
+ - * / %

Symbols of arithmetic operations

&& ||

Symbols of logical operations

= += *=

Characters assignment operators

Operation symbols are used in expressions and have sense when appropriate operands are given to
them. Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and
semicolon.
Operation symbols, punctuation marks, and spaces are used to separate language elements from each
other.
This section contains the description of the following topics:
Expressions
Arithmetic Operations
Assignment Operations
Operations of Relation
Boolean Operations
Bitwise Operations
Other Operations
Priorities and Operations Order

2000-2016, MetaQuotes Software Corp.

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

// several expressions are located in one line

one expression is divided into several lines

x = (y * z) /
(w + 2) + 127;

An expression that ends with a semicolon (;) is an operator.


See also
Precedence Rules

2000-2016, MetaQuotes Software Corp.

106

Language Basics

Arithmetic Operations
Arithmetic operations include additive and multiplicative operations:
Sum of variables

i = j + 2;

Difference of variables

i = j - 3;

Changing the sign

x = - x;

Product of variables

z = 3 * x;

Division quotient

i = j / 5;

Remainder of division

minutes = time % 60;

Adding 1 to the variable value

i++;

Adding 1 to the variable value

++i;

Subtracting 1 from the variable value

k--;

Subtracting 1 from the variable value

--k;

Increment and decrement operations are applied only to variables, they can't be applied to constants.
The prefix increment (++i) and decrement (--k) are applied to the variable right before this variable is
used in an expression.
Post-increment (i++) and post-decrement (k--) are applied to the variable right after this variable is
used in an expression.
Important Notice
int i=5;
int k = i++ + ++i;

Computational problems may occur while moving the above expression from one programming
environment to another one (for example, from Borland C++ to MQL5). In general, the order of
computations depends on the compiler implementation. In practice, there are two ways to implement
the post-decrement (post-increment):
1. The post-decrement (post-increment) is applied to the variable after calculating the whole
expression.
2. The post-decrement (post-increment) is applied to the variable immediately at the operation.
Currently the first way of post-decrement (post-increment) calculation is implemented in MQL5. But
even knowing this peculiarity, it is not recommended to experiment with its use.
Examples:
int a=3;
a++;

// valid expression

int b=(a++)*3;

// invalid expression

See also
Precedence Rules

2000-2016, MetaQuotes Software Corp.

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;

Subtracting x from the y variable

y -= x;

Multiplying the y variable by x

y *= x;

Dividing the y variable by x

y /= x;

Reminder of division of the y variable by x

y %= x;

Shift of the binary representation of y to the right by x bits

y >>= x;

Shift of the binary representation of y to the left by x bits

y <<= x;

AND bitwise operation of binary representations of y and x

y &= x;

OR bitwise operation of binary representations of y and x

y |= x;

Excluding OR bitwise operation of binary representations of y and x

y ^= x;

Bitwise operations can be applied to integers only. 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

2000-2016, MetaQuotes Software Corp.

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;

True if a is not equal to b

a != b;

True if a is less than b

a < b;

True if a is greater than b

a > b;

True if a is less than or equal to b

a <= b;

True if a is greater than or equal to b

a >= b;

The equality of two real numbers can't be compared. In most cases, two seemingly identical numbers
can be unequal because of different values in the 15th decimal place. In order to correctly compare two
real numbers, compare the normalized difference of these numbers with zero.
Example:
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double first=0.3;
double second=3.0;
double third=second-2.7;
if(first!=third)
{
if(CompareDoubles(first,third))
printf("%.16f and %.16f are equal",first,third);
}
}
// Result: 0.3000000000000000

0.2999999999999998

are equal

See also
Precedence Rules

2000-2016, MetaQuotes Software Corp.

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

Logical Operation OR (||)


Logical OR operation (||) of x and y values. The expression value is TRUE (1), if x or y value is true
(not null). Otherwise - FALSE (0).
if(x<0 || x>=max_bars) Print("out of range");

Logical Operation AND (&&)


Logical operation AND (&&) of x and y values. The expression value is TRUE (1), if the values of x and
y are true (not null). Otherwise - FALSE (0).

Brief Estimate of Boolean Operations


The scheme of the so called "brief estimate" is applied to boolean operations, i.e. the calculation of
the expression is terminated when the result of the expression can be precisely estimated.
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- the first example of the brief estimate
if(func_false() && func_true())
{
Print("Operation &&: You will never see this expression");
}
else
{

Print("Operation &&: Result of the first expression is false, so the second wasn't calculated
}
//--- the second example of the brief estimate
if(!func_false() || !func_true())
{

Print("Operation ||: Result of the first expression is true, so the second wasn't calculated"
}
else
{
Print("Operation ||: You will never see this expression");
}
}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

// The result will be:


// a = 97

b = -98

Right Shift
The binary representation of x is shifted to the right by y digits. If the value to shift is of the unsigned
type, the logical right shift is made, i.e. the freed left-side bits will be filled with zeroes.
If the value to shift is of a sign type, the arithmetic right shift is made, i.e. the freed left-side digits
will be filled with the value of a sign bit (if the number is positive, the value of the sign bit is 0; if the
number is negative, the value of the sign bit is 1).
x = x >> y;

Example:
char a='a',b='b';
Print("Before:

a = ",a, "

b = ",b);

//--- shift to the right


b=a>>1;
Print("After:

a = ",a, "

b = ",b);

// The result will be:


// Before:

a = 97

b = 98

// After:

a = 97

b = 48

Left Shift
The binary representation of x is shifted to the left by y digits, the freed right-side digits are filled
with zeros.
x = x << y;

Example:
char a='a',b='b';
Print("Before:

a = ",a, "

b = ",b);

//--- shift to the left


b=a<<1;
Print("After:

a = ",a, "

b = ",b);

2000-2016, MetaQuotes Software Corp.

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.

Bitwise AND Operation


The bitwise AND operation of binary-coded x and y representations. The value of the expression
contains a 1 (TRUE) in all digits where both x and y contain non-zero, and it contains 0 (FALSE) in all
other digits.
b = ((x & y) != 0);

Example:
char a='a',b='b';
//--- AND operation
char c=a&b;
Print("a = ",a,"

b = ",b);

Print("a & b = ",c);


// The result will be:
// a = 97

b = 98

// a & b = 96

Bitwise OR Operation
The bitwise OR operation of binary representations of x and y. The value of the expression contains 1
in all digits where x or y does not contain 0, and it contains 0 in all other digits.
b = x | y;

Example:
char a='a',b='b';
//--- OR operation
char c=a|b;
Print("a = ",a,"

b = ",b);

Print("a | b = ",c);
// The result will be:
// a = 97

b = 98

// a | b = 99

Bitwise Exclusive Operation OR


The bitwise exclusive OR (eXclusive OR) operation of binary representations of x and y. The value of
the expression contains a 1 in all digits where x and y have different binary values, and it contains 0 in
all other digits.
b = x ^ y;

Example:

2000-2016, MetaQuotes Software Corp.

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

Bitwise operations are performed with integers only.


See also
Precedence Rules

2000-2016, MetaQuotes Software Corp.

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.

Calling Function with x1, x2 ,..., xn Arguments


Each argument can represent a constant, variable, or expression of the corresponding type. The
arguments passed are separated by commas and must be inside of parentheses, the opening
parenthesis must follow the name of the called function.
The expression value is the value returned by the function. If the return value is of void type, such
function call cannot be placed to the right in the assignment operation. Please make sure that the
expressions x1,..., xn are executed exactly in this order.
Example:
int length=1000000;
string a="a",b="b",c;
//---Other Operations
int start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c = a + b' = ",(stop-start)," milliseconds, i = ",i);

Comma Operation ( , )
Expressions separated by commas are executed from left to right. All side effects of the left
expression calculation can appear before the right expression is calculated. The result type and value
coincide with those of the right expression. The list of parameters to be passed (see above) can be
considered as an example.
Example:

2000-2016, MetaQuotes Software Corp.

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;

Scope Resolution Operation ( :: )


Each function in a mql5 program has its own execution scope. For example, the Print() system function
is performed in a global scope. Imported functions are called in the scope of the corresponding import.
Method functions of classes have the scope of the corresponding class. The syntax of the scope
resolution operation is as follows:
[Scope_name]::Function_name(parameters)

If there is no scope name, this is the explicit direction to use the global scope. If there is no scope
resolution operation, the function is sought in the nearest scope. If there is no function in the local
scope, the search is conducted in the global scope.
The scope resolution operation is also used to define function-class member.
type Class_name::Function_name(parameters_description)
{
// function body
}

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

2000-2016, MetaQuotes Software Corp.

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

Operation of Obtaining Data Type Size or Size of Any Data Type

2000-2016, MetaQuotes Software Corp.

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

The size is calculated at the compilation stage.


See also
Precedence Rules

2000-2016, MetaQuotes Software Corp.

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

From left to right

!
~

++
-(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

From left to right

Addition
Subtraction

From left to right

<<
>>

Left shift
Right shift

From left to right

<
<=
>
>=

Less than
Less than or equal
Greater than
Greater than or equal

From left to right

==
!=

Equal
Not equal

From left to right

&

Bitwise AND operation

From left to right

Bitwise exclusive OR

From left to right

Bitwise OR operation

From left to right

&&

Logical AND operation

From left to right

||

Logical OR operation

From left to right

?:

Conditional Operator

Right to left

=
*=

Assignment
Multiplication with assignment

Right to left

2000-2016, MetaQuotes Software Corp.

119

Language Basics

/=
%=
+=
-=
<<=
>>=
&=
^=
|=

Division with assignment


Module with assignment
Addition with assignment
Subtraction with assignment
Left shift with assignment
Right shift with assignment
Bitwise AND with assignment
Exclusive OR with assignment
Bitwise OR with assignment

Comma

From left to right

To change the operation execution order, parenthesis that are of higher priority are used.

2000-2016, MetaQuotes Software Corp.

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

One or more operators of any type, enclosed in


curly braces {}

Expression operator (;)

Any expression that ends with a semicolon (;)

return operator

Terminates the current function and returns


control to the calling program

if-else conditional operator

Is used when it's necessary to make a choice

?: conditional operator

A simple analog of the if-else conditional


operator

switch selection operator

Passes control to the operator,


corresponds to the expression value

while loop operator

Performs an operator until the expression


checked becomes false. The expression is
checked before each iteration

for loop operator

Performs an operator until the expression


checked becomes false. The expression is
checked before each iteration

do-while loop operator

Performs an operator until the expression


checked becomes false. The end condition is
checked, after each loop. The loop body is
always executed at least once.

break operator

Terminates the execution of the nearest


attached external operator switch, while, dowhile or for

continue operator

Passes control to the beginning of the nearest


external loop operator while, do-while or for

new operator

Creates an object of the appropriate size and


returns a descriptor of the created object.

delete operator

Deletes the object created by the new operator

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)

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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:

Function Calling Operator


Function_name (argument1,..., argumentN);
FileClose(file);

Empty Operator
Consists only of a semicolon (;) and is used to denote an empty body of a control operator.
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects

2000-2016, MetaQuotes Software Corp.

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;

// this operator can be removed

The right brace of the function means implicit execution of the return operator without expression.
What can be returned: simple types, simple structures, object pointers. With the return operator you
can't return any arrays, class objects, variables of compound structure type.
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects

2000-2016, MetaQuotes Software Corp.

125

Language Basics

If-Else Conditional Operator


The IF - ELSE operator is used when a choice must be made. Formally, the syntax is as follows:
if (expression)
operator1
else
operator2

If the expression is true, operator1 is executed and control is given to the operator that follows
operator2 (operator2 is not executed). If the expression is false, operator2 is executed.
The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators
with omitted else part. In this case, else addresses to the nearest previous if operator in the same
block that has no else part.
Examples:
//--- The else part refers to the second if operator:
if(x>1)
if(y==2) z=5;
else

z=6;

//--- The else part refers to the first if operator:


if(x>l)
{
if(y==2) z=5;
}
else

z=6;

//--- Nested operators


if(x=='a')
{
y=1;
}
else if(x=='b')
{
y=2;
z=3;
}
else if(x=='c')
{
y=4;
}
else Print("ERROR");

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

2000-2016, MetaQuotes Software Corp.

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

This entry is equivalent to the following:


double true_range;
if(High==Low)true_range=0;

// if High and Low are equal

else true_range=(Close-Open)/(High-Low); // if the range is not null

Operator Use Restrictions


Based on the value of "expression1", the operator must return one of the two values - either
"expression2" or "expression3". There are several limitations to these expressions:
1. Do not mix user-defined type with simple type or enumeration. NULL can be used for the pointer.
2. If types of values are simple, the operator will be of the maximum type (see Type casting).
3. If one of the values is an enumeration and the second one is of a numeric type, the enumeration is
replaced by int and the second rule is applied.
4. If both values are enumerations, their types must be identical, and the operator will be of type
enumeration.
Restrictions for the user-defined types (classes or structures):
a) Types must be identical or one should be derived from the other one.
b) If types are not identical (inheritance), then the child is implicitly cast to the parent, i.e. the
operator will be of the parent type.
c) Do not mix object and the pointer both expressions must be either objects or pointers. NULL can
be used for the pointer.
Note
Be careful when using the conditional operator as an argument of an overloaded function, because the
type of the result of a conditional operator is defined at the time of program compilation. And this
type is determined as the larger of the types "expression2" and "expression3".
Example:

2000-2016, MetaQuotes Software Corp.

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

// warning on implicit casting to string

func(!Expression1?Expression2:Expression3);

// warning on implicit casting to string

}
//

Result:

//

double argument: 3.141592653589793

//

string argument: 3.1415926

//

string argument: 3.141592653589793

//

string argument: 3.1415926

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

2000-2016, MetaQuotes Software Corp.

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;

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

130

Language Basics

While Loop Operator


The while operator consists of a checked expression and the operator, which must be fulfilled:
while(expression)
operator;

If the expression is true, the operator is executed until the expression becomes false. If the
expression is false, the control is passed to the next operator. The expression value is defined before
the operator is executed. Therefore, if the expression is false from the very beginning, the operator
will not be executed at all.
Note
If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the 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

2000-2016, MetaQuotes Software Corp.

131

Language Basics

For Loop Operator


The for operator consists of three expressions and an executable operator:
for(expression1; expression2; expression3)
operator;

Expression1 describes the loop initialization. Expression2 checks the conditions of the loop
termination. If it is true, the loop body for is executed. The loop repeats expression2 until it becomes
false. If it is false, the loop is terminated, and control is given to the next operator. Expression3 is
calculated after each iteration.
The for operator is equivalent to the following succession of operators:
expression1;
while(expression2)
{
operator;
expression3;
};

Any of the three or all three expressions can be absent in the for operator, but the semicolons (;) that
separate them must not be omitted. If expression2 is omitted, it is considered constantly true. The
for(;;) operator is a continuous loop, equivalent to the while(1) operator. Each expression 1 or 3 can
consist of several expressions combined by a comma operator ','.
Note
If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the 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

2000-2016, MetaQuotes Software Corp.

132

Language Basics

Loop Operator do while


The for and while loops check the termination at the beginning, not at the end of a loop. The third
loop operator do - while checks the condition of termination at the end, after each loop iteration. The
loop body is always executed at least once.
do
operator;
while(expression);

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

135

Language Basics

Object Create Operator new


The new operator automatically creates an object of a corresponding size, calls the object constructor
and returns a descriptor of created object. In case of failure, the operator returns a null descriptor
that can be compared with the NULL constant.
The new operator can be applied only to class objects. It can't be applied to structures.
The operator shall not be used to create arrays of objects. To do this, use the ArrayResize() function.
Example:
//+------------------------------------------------------------------+
//| Figure creation

//+------------------------------------------------------------------+
void CTetrisField::NewShape()
{
m_ypos=HORZ_BORDER;
//--- randomly create one of the 7 possible shapes
int nshape=rand()%7;
switch(nshape)
{
case 0: m_shape=new CTetrisShape1; break;
case 1: m_shape=new CTetrisShape2; break;
case 2: m_shape=new CTetrisShape3; break;
case 3: m_shape=new CTetrisShape4; break;
case 4: m_shape=new CTetrisShape5; break;
case 5: m_shape=new CTetrisShape6; break;
case 6: m_shape=new CTetrisShape7; break;
}
//--- draw
if(m_shape!=NULL)
{
//--- pre-settings
m_shape.SetRightBorder(WIDTH_IN_PIXELS+VERT_BORDER);
m_shape.SetYPos(m_ypos);
m_shape.SetXPos(VERT_BORDER+SHAPE_SIZE*8);
//--- draw
m_shape.Draw();
}
//--}

It should be noted that object descriptor is not a pointer to memory address.


An object created with the new operator must be explicitly removed using the delete operator.
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects

2000-2016, MetaQuotes Software Corp.

136

Language Basics

Object Delete Operator delete


The delete operator deletes an object created by the new operator, calls the corresponding class
destructor and frees up memory occupied by the object. A real descriptor of an existing object is used
as an operand. After the delete operation is executed, the object descriptor becomes invalid.
Example:
//--- delete figure
delete m_shape;
m_shape=NULL;
//--- create a new figure
NewShape();

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

2000-2016, MetaQuotes Software Corp.

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 type

linfunc (double a, double b) // function name and parameter list


{
// composite operator
return (a + b);

// return value

The return operator can return the value of an expression located in this operator. If necessary, the
expression value is converted to the function result type. 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

2000-2016, MetaQuotes Software Corp.

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,

// default value 0.0001 declared

int n,

// default value is not specified !

bool b,

// default value is not specified !

string s="passed string")


{
}

See also
Overload, Virtual Functions, Polymorphism

2000-2016, MetaQuotes Software Corp.

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

// Wrong call. The first parameter must be presented.

somefunc(3.14);

// Correct call

somefunc(3.14,0.0002);

// Correct call

somefunc(3.14,0.0002,10);

// Correct call

When calling a function, one may not skip parameters, even those having default values:
somefunc(3.14, , 10);

// Wrong call -> the second parameter was skipped.

See also
Overload, Virtual Functions, Polymorphism

2000-2016, MetaQuotes Software Corp.

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

a and b before call: 14 8

//

a and b after call: 14 8

The second method is to pass by reference. In this case, reference to a parameter (not its value) is
passed to a function parameter. Inside the function, it is used to refer to the actual parameter
specified in the call. This means that the parameter changes will affect the argument used to call the
function.
//+------------------------------------------------------------------+
//| Passing parameters by reference

//+------------------------------------------------------------------+
double SecondMethod(int &i,int &j)
{
double res;
//--i*=2;
j/=2;
res=i+j;

2000-2016, MetaQuotes Software Corp.

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

a and b before call: 14 8

//

a and b after call: 28 4

MQL5 uses both methods, with one exception: arrays, structure type variables and class objects are
always passed by reference. In order to avoid changes in actual parameters (arguments passed at
function call) use the access specifier const. 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)
{

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

// Summation for the double

}
aver=sum/size;

// Just divide the sum by the number

//--Print("Calculation of the average for an array of double type");


return aver;
}
//+------------------------------------------------------------------+
//| The calculation of average for an array of int type

//+------------------------------------------------------------------+
double AverageFromArray(const int & array[],int size)
{
if(size<=0) return 0.0;
double aver=0.0;
int sum=0;
//--for(int i=0;i<size;i++)
{
sum+=array[i];

// Summation for the int

}
aver=(double)sum/size;// Give the amount of type double, and divide
//--Print("Calculation of the average for an array of int type");
return aver;
}

Each function contains the message output via the Print() function;
Print("Calculation of the average for an array of int type");

The compiler selects a necessary function in accordance with the types of arguments and their

2000-2016, MetaQuotes Software Corp.

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.

Algorithm of Choosing an Overloaded Function


1. Use strict matching (if possible).
2. Try standard type increase.
3. Try standard typecasting.
The standard type increase is better than other standard conversions. Increase is the conversion of
float to double, of bool, char, short or enum to int. Typecasting of arrays of similar integer types also
belongs to typecasting. Similar types are: bool, char, uchar, since all the three types are single-byte
integers; double-byte integers short and ushort; 4-byte integers int, uint, and color; long, ulong, and
datetime.
Of course, the strict matching is the best. To achieve such a consistency typecasting can be used. The
compiler cannot cope with ambiguous situations. Therefore you should not rely on subtle differences of
types and implicit conversions that make the overloaded function unclear.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

re; // Real part

double

im; // Imaginary part

//--- Constructors
complex():re(0.0),im(0.0) {

complex(const double r):re(r),im(0.0) {

complex(const double r,const double i):re(r),im(i) {

complex(const complex &o):re(o.re),im(o.im) { }


//--- Arithmetic operations
complex

Add(const complex &l,const complex &r) const;

// Addition

complex

Sub(const complex &l,const complex &r) const;

// Subtraction

complex

Mul(const complex &l,const complex &r) const;

// Multiplication

complex

Div(const complex &l,const complex &r) const;

// Division

};

Now, in our code we can declare variables representing complex numbers, and work with them.
For example:
void OnStart()
{
//--- Declare and initialize variables of a complex type
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f,

b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);

//--- Sum up two numbers


complex z;

2000-2016, MetaQuotes Software Corp.

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

The full example of the script:


//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f,

b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);

//a.re=5;
//a.im=1;
//b.re=-1;
//b.im=-5;
//--- Sum up two numbers
complex z=a+b;
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers
z=a*b;
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a/b;

2000-2016, MetaQuotes Software Corp.

148

Language Basics
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--}
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers

//+------------------------------------------------------------------+
struct complex
{
double

re; // Real part

double

im; // Imaginary part

//--- Constructors
complex():re(0.0),im(0.0) {

complex(const double r):re(r),im(0.0) {

complex(const double r,const double i):re(r),im(i) {

complex(const complex &o):re(o.re),im(o.im) { }


//--- Arithmetic operations
complex

Add(const complex &l,const complex &r) const;

// Addition

complex

Sub(const complex &l,const complex &r) const;

// Subtraction

complex

Mul(const complex &l,const complex &r) const;

// Multiplication

complex

Div(const complex &l,const complex &r) const;

// Division

//--- Binary operators


complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }
};
//+------------------------------------------------------------------+
//| Addition

//+------------------------------------------------------------------+
complex complex::Add(const complex &l,const complex &r) const
{
complex res;
//--res.re=l.re+r.re;
res.im=l.im+r.im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Subtraction

//+------------------------------------------------------------------+
complex complex::Sub(const complex &l,const complex &r) const
{
complex res;
//--res.re=l.re-r.re;
res.im=l.im-r.im;
//--- Result
return res;

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

const; // Unary minus

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

//--- Divide the two numbers

2000-2016, MetaQuotes Software Corp.

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

CString str("abcdefghijklmnopqrstuvwxyz[ ]CS");


string

res;

//--- Make up a phrase using symbols from the str variable


for(int i=0,n=ArraySize(x);i<n;i++)
{
res+=ShortToString(str[x[i]]);
}

2000-2016, MetaQuotes Software Corp.

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++)
{

2000-2016, MetaQuotes Software Corp.

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

CRow(const CRow &r) { this=r;

}
}

CRow(const double &array[]);


~CRow(void){};
//--- Number of elements in the row
int

Size(void) const

{ return(ArraySize(m_array));}

//--- Returns a string with values


string

String(void) const;

//--- Indexing operator


double

operator[](int i) const

{ return(m_array[i]);

//--- Assignment operators


void

operator=(const double

void

operator=(const CRow & r);

&array[]); // An array
// Another CRow object

double

operator*(const CRow &o);

// CRow object for multiplication

};
//+------------------------------------------------------------------+
//| Constructor for initializing a row with an array

//+------------------------------------------------------------------+
void

CRow::CRow(const double &array[])

{
int size=ArraySize(array);
//--- If the array is not empty
if(size>0)
{
ArrayResize(m_array,size);
//--- Fill with values
for(int i=0;i<size;i++)
m_array[i]=array[i];
}
//---

2000-2016, MetaQuotes Software Corp.

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
{

2000-2016, MetaQuotes Software Corp.

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

const { return(Rows()>0? m_rows[0].Size():0); }

//--- Returns the value of the column in the form of a CRow row
CRow

GetColumnAsRow(const int col_index) const;

//--- Returns a string with the matrix values


string

String(void) const;

//--- The indexing operator returns a string by its number


CRow *operator[](int i) const

{ return(GetPointer(m_rows[i]));

//--- Addition operator


CMatrix

operator+(const CMatrix &m);

//--- Multiplication operator


CMatrix

operator*(const CMatrix &m);

//--- Assignment operator


CMatrix

*operator=(const CMatrix &m);

};
//+------------------------------------------------------------------+
//| A default constructor, create an array of rows of zero size

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

2000-2016, MetaQuotes Software Corp.

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

CMatrix::GetColumnAsRow(const int col_index) const

{
//--- A variable to get the values from the column
CRow row();
//--- The number of rows in the matrix
int rows=Rows();
//--- If the number of rows is greater than zero, execute the operation
if(rows>0)
{
//--- An array to receive the values of the column with index col_index
double array[];
ArrayResize(array,rows);
//--- Filling the array
for(int i=0;i<rows;i++)
{

//--- Check the number of the column for row i - it may exceed the boundaries of the array
if(col_index>=this[i].Size())
{
Print(__FUNCSIG__,": Error! Column number ",col_index,"> row size ",i);
break; // row will be uninitialized object
}
array[i]=this[i][col_index];
}
//--- Create a CRow row based on the array values
row=array;
}
//--- Result
return(row);
}
//+------------------------------------------------------------------+
//| Addition of two matrices

//+------------------------------------------------------------------+
CMatrix CMatrix::operator+(const CMatrix &m)
{
//--- The number of rows and columns in the passed matrix
int cols=m.Cols();
int rows=m.Rows();
//--- The matrix to receive the addition results
CMatrix res(rows);
//--- The sizes of the matrix must match

2000-2016, MetaQuotes Software Corp.

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
{

2000-2016, MetaQuotes Software Corp.

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

the passed matrix

for(int i=0;i<rows;i++) this[i]=m[i];


//--return(GetPointer(this));
}
//+------------------------------------------------------------------+
//| String representation of the matrix

//+------------------------------------------------------------------+
string CMatrix::String(void) const
{
string out="";
int rows=Rows();
//--- Form string by string
for(int i=0;i<rows;i++)
{
out=out+this[i].String()+"\r\n";
}
//--- Result
return(out);
}

See also
Overloading, Arithmetic Operations, Function Overloading, Precedence Rules

2000-2016, MetaQuotes Software Corp.

159

Language Basics

Description of External Functions


External functions defined in another module must be explicitly described. The description includes
returned type, function name and series of input parameters with their types. The absence of such a
description can lead to errors when compiling, building, or executing a program. When describing an
external object, use the keyword #import indicating the module.
Examples:
#import "user32.dll"
int

MessageBoxW(int hWnd ,string szText,string szCaption,int nType);

int

SendMessageW(int hWnd,int Msg,int wParam,int lParam);

#import "lib.ex5"
double

round(double value);

#import

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

// call of the class method

Print(::GetLastError());

// call of the MQL5 function

Print(kernel32::GetLastError()); // call of the DLL library function from kernel32.dll


Print(lib::GetLastError());

// call of the EX5 library function from lib.ex5

}
};
void OnStart()
{
CFoo foo;
foo.func();
}

2000-2016, MetaQuotes Software Corp.

160

Language Basics

See also
Overload, Virtual Functions, Polymorphism

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

162

Language Basics

Event Handling Functions


The MQL5 language provides processing of some predefined events. Functions for handling these
events must be defined in a MQL5 program; function name, return type, composition of parameters (if
there are any) and their types must strictly conform to the description of the event handler function.
The event handler of the client terminal identifies functions, handling this or that event, by the type
of return value and type of parameters. If other parameters, not corresponding to below descriptions,
are specified for a corresponding function, or another return type is indicated for it, such a function
will not be used as an event handler.

OnStart
The 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

Successful initialization, testing of the Expert


Advisor can be continued.
This code means the same as a null value the
Expert Advisor has been successfully initialized
in the tester.

INIT_FAILED

Initialization failed; there is no point in


continuing testing because of fatal errors. For
example, failed to create an indicator that is
required for the work of the Expert Advisor.

2000-2016, MetaQuotes Software Corp.

163

Language Basics

This return value means the same as a value


other than zero - initialization of the Expert
Advisor in the tester failed.
INIT_PARAMETERS_INCORRECT

This value means the incorrect set of input


parameters. The result string containing this
return code is highlighted in red in the general
optimization table.
Testing for the given set of parameters of the
Expert Advisor will not be executed, the agent is
free to receive a new task.
Upon receiving this value, the strategy tester
will reliably not pass this task to other agents
for retry.

INIT_AGENT_NOT_SUITABLE

No errors during initialization, but for some


reason the agent is not suitable for testing. For
example, not enough memory, no OpenCL
support, etc.
After the return of this code, the agent will not
receive tasks until the end of this optimization.

The OnInit() function of the void type always denotes successful initialization.

OnDeinit
The OnDeinit() function is called during deinitialization and is the Deinit event handler. It must be
declared as the void type and should have one parameter of the const int type, which contains the
code of deinitialization reason. If a different type is declared, the compiler will generate a warning,
but the function will not be called. For scripts the Deinit event is not generated and therefore the
OnDeinit() function can't be used in scripts.
void OnDeinit(const int reason);

The Deinit event is generated for Expert Advisors and indicators in the following cases:
before reinitialization due to the change of a symbol or chart period, to which the mql5 program is

attached;
before reinitialization due to the change of input parameters;
before unloading the mql5 program.

OnTick
The NewTick event is generated for Expert Advisors only when a new tick for a symbol is received, to
the chart of which the Expert Advisor is attached. It's useless to define the OnTick() function in a
custom indicator or script, because the NewTick event is not generated for them.
The Tick event is generated only for Expert Advisors, but this does not mean that Expert Advisors
required the OnTick() function, since not only NewTick events are generated for Expert Advisors, but
also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type,
with no parameters:
void OnTick();

2000-2016, MetaQuotes Software Corp.

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

OrderSendAsync functions and its further execution;


Sending a trade request via the terminal graphical interface and its further execution;
Pending orders and stop orders activation on the server;
Performing operations on a trade server side.

The following trade transactions are performed as a result of these actions:


handling a trade request;
changing open orders;
changing orders history;
changing deals history;

2000-2016, MetaQuotes Software Corp.

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,

// trade transaction structure

const MqlTradeRequest&

request,

// request structure

const MqlTradeResult&

result

// result structure

);

The handler contains three parameters:


trans - this parameter gets MqlTradeTransaction structure describing a trade transaction applied to

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.

The last two request and result parameters are filled by


values
only
for
TRADE_TRANSACTION_REQUEST type transaction, data on transaction can be received from type
parameter of trans variable. Note that in this case, request_id field in result variable contains ID of
request trade request, after the execution of which the trade transaction described in trans variable
has been performed. Request ID allows to associate the performed action (OrderSend or
OrderSendAsync functions call) with the result of this action sent to OnTradeTransaction().
One trade request manually sent from the terminal or via OrderSend()/OrderSendAsync() functions can
generate several consecutive transactions on the trade server. Priority of these transactions' arrival at
the terminal is not guaranteed. Thus, you should not expect that one group of transactions will arrive
after another one when developing your trading algorithm. Besides, transactions can be lost during
delivery from the server to the terminal.
All types of trade transactions are described in ENUM_TRADE_TRANSACTION_TYPE enumeration.
MqlTradeTransaction structure describing a trade transaction is filled in different ways

depending on a transaction type. For example, only type field (trade transaction type) must be
analyzed for TRADE_TRANSACTION_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

2000-2016, MetaQuotes Software Corp.

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.

One OnTrade call corresponds to one or several OnTradeTransaction calls.


OnTrade is called after appropriate OnTradeTransaction calls.

OnTester
The OnTester() function is the handler of the Tester event that is automatically generated after a
history testing of an Expert Advisor on the chosen interval is over. The function must be defined with
the double type, with no parameters:
double OnTester();

The function is called right before the call of OnDeinit() and has the same type of the return value double. OnTester() can be used only in the testing of Expert Advisors. Its main purpose is to calculate
a certain value that is used as the Custom max criterion in the genetic optimization of input
parameters.
In the genetic optimization descending sorting is applied to results within one generation. I.e. from
the point of view of the optimization criterion, the best results are those with largest values (for the
Custom max optimization criterion values returned by the OnTester function are taken into account).
In such a sorting, the worst values are positioned at the end and further thrown off and do not
participate in the forming of the next generation.

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

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"

2000-2016, MetaQuotes Software Corp.

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

mouse move events


CHART_EVENT_MOUSE_MOVE=true is set for the chart);

and

CHARTEVENT_OBJECT_CREATE

event
of
graphical
CHART_EVENT_OBJECT_CREATE=true is set for the chart);

mouse

click

object

events

creation

(if
(if

CHARTEVENT_OBJECT_CHANGE event of change of an object property via the properties dialog;


CHARTEVENT_OBJECT_DELETE

event
of
graphical
CHART_EVENT_OBJECT_DELETE=true is set for the chart);

object

deletion

(if

CHARTEVENT_CLICK event of a mouse click on the chart;


CHARTEVENT_OBJECT_CLICK event of a mouse click in a graphical object belonging to the chart;
CHARTEVENT_OBJECT_DRAG event of a graphical object move using the mouse;
CHARTEVENT_OBJECT_ENDEDIT event of the finished text editing in the entry box of the

LabelEdit graphical object;


CHARTEVENT_CHART_CHANGE event of chart changes;

2000-2016, MetaQuotes Software Corp.

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

const long& lparam,

// Parameter of type long event

const double& dparam, // Parameter of type double event


const string& sparam

// Parameter of type string events

);

For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through these parameters
are listed in the table below.
Event

Value of the id
parameter

Value of
lparam
parameter

the

CHARTEVENT_KE
YDOWN

code
of
pressed key

Mouse events (if


property
CHART_EVENT_
MOUSE_MOVE=tr
ue is set for the
chart)

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 string value


of a bit mask
describing
the
status
of
keyboard buttons

the X coordinate

the Y coordinate

The string value


of a bit mask
describing
the
status of mouse
buttons

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

2000-2016, MetaQuotes Software Corp.

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

Value set by the


EventChartCusto
m() function

Value set by the


EventChartCusto
m() function

Value set by the


EventChartCusto
m() function

OnCalculate
The OnCalculate() function is called only in custom indicators when it's necessary to calculate the
indicator values by the Calculate event. This usually happens when a new tick is received for the
symbol, for which the indicator is calculated. This indicator is not required to be attached to any price
chart of this symbol.
The OnCalculate() function must have a return type int. There are two possible definitions. Within one
indicator you cannot use both versions of the function.
The first form is intended for those indicators that can be calculated on a single data buffer. An
example of such an indicator is Custom Moving Average.
int OnCalculate (const int rates_total,

// size of the price[] array

const int prev_calculated,

// bars handled on a previous call

const int begin,

// where the significant data start from

const double& price[]

// array to calculate

);

As the price[] array, one of timeseries or a calculated buffer of some indicator can be passed. To

2000-2016, MetaQuotes Software Corp.

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

int handle_customMA=iCustom(Symbol(),PERIOD_CURRENT, "Custom Moving Average",13,0, MODE_EMA,PRIC


if(handle_customMA>0)
Print("handle_customMA = ",handle_customMA);
else

Print("Cannot open or not EX5 file '"+terminal_path+"\\MQL5\\Indicators\\"+"Custom Moving Ave


}

In this example, the last parameter passed is the PRICE_TYPICAL value (from the
ENUM_APPLIED_PRICE enumeration), which indicates that the custom indicator will be built on typical
prices obtained as (High+Low+Close)/3. If this parameter is not specified, the indicator is built based
on PRICE_CLOSE values, i.e. closing prices of each bar.
Another example that shows passing of the indicator handler as the last parameter to specify the
price[] array, is given in the description of the iCustom() function.

The second form is intended for all other indicators, in which more than one time series is used for
calculations.

2000-2016, MetaQuotes Software Corp.

171

Language Basics
int OnCalculate (const int rates_total,

// size of input time series

const int prev_calculated,

// bars handled in previous call

const datetime& time[],

// Time

const double& open[],

// Open

const double& high[],

// High

const double& low[],

// Low

const double& close[],

// Close

const long& tick_volume[],

// Tick Volume

const long& volume[],

// Real Volume

const int& spread[]

// Spread

);

Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and low prices
and close prices of the current time frame. The time[] parameter contains an array with open time
values, the spread[] parameter has an array containing the history of spreads (if any spread is
provided for the traded security). The parameters of volume[] and tick_volume[] contain the history of
trade and tick volume, respectively.
To determine the indexing direction of time[], open[], high[], low[], close[], tick_volume[], volume[]
and spread[], call 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

//---- plot Line


#property indicator_label1

"Line"

#property indicator_type1

DRAW_LINE

#property indicator_color1

clrDarkBlue

#property indicator_style1

STYLE_SOLID

#property indicator_width1

2000-2016, MetaQuotes Software Corp.

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

Print("time[0] = ",time[0]," time[rates_total-1] = ",time[rates_total-1]);


//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+

See also
Running Programs, Client Terminal Events, Working with Events

2000-2016, MetaQuotes Software Corp.

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

Complex or compound types:


Structures are composite data types, constructed using other types.
struct MyTime
{
int hour;

// 0-23

int minute;

// 0-59

int second;

// 0-59

};
...
MyTime strTime; // Variable of the previously declared structure MyTime

You can't declare variables of the structure type until you declare the structure.
Arrays
Array is the indexed sequence of identical-type data:
int

a[50];

double m[7][50];

// One-dimensional array of 50 integers.


// Two-dimensional array of seven arrays,
// each of them consisting of 50 numbers.

MyTime t[100];

// Array containing elements such as MyTime

2000-2016, MetaQuotes Software Corp.

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,

// size of the price[] array

const int prev_calculated,

// bars handled on a previous call

const int begin,

// where the significant data start from

const double& price[]

// array to calculate

);

To access members of structures and classes use the following qualifiers:


public allows unrestricted access to the variable or class method
protected allows access from methods of this class, as well as from methods of publicly inherited

classes. Other access is impossible;


private allows access to variables and class methods only from methods of the same class.
virtual applies only to class methods (but not to methods of structures) and tells the compiler that

this method should be placed in the table of virtual functions of the class.

Storage Classes
There are three storage classes: static, input and extern. These modifiers of a storage class explicitly
indicate to the compiler that corresponding variables are distributed in a pre-allocated area of
memory, which is called the global pool. Besides, these modifiers indicate the special processing of
variable data. If a variable declared on a local level is not a static one, memory for such a variable is
allocated automatically at a program stack. Freeing of memory allocated for a non-static array is also
performed automatically when going beyond the visibility area of the block, in which the array is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects, Static Members of a Class

2000-2016, MetaQuotes Software Corp.

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;

// local variable of the function

{
int i=10;

// function variable

Print("Inside block i = ",i); // result is

i=10;

}
Print("Outside block i = ",i);

// result is

i=5;

This means that while the internal block is running, it sees values of its own local identifiers, not the
values of identifiers with identical names in the external block.
Example:
void OnStart()
{
//--int i=5;

// local variable of the function

for(int i=0;i<3;i++)
Print("Inside for i = ",i);
Print("Outside the block i = ",i);
}
/* Execution result

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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;

2000-2016, MetaQuotes Software Corp.

178

Language Basics
z[i]=OrderOpenPrice();
}
x=i;
y=calculated_tp;
}

Parameters passed by reference can't be initialized by default values.


Maximum 64 parameters can be passed into a function.
See also
Input Variables, Data Types, Encapsulation and Extensibility of Types,Initialization of Variables,
Visibility Scope and Lifetime of Variables, Creating and Deleting Objects

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

180

Language Basics
Lifetime of Variables, Creating and Deleting Objects, Static Class Members

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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 ENUM_MA_METHOD MA_Method=MODE_SMMA;

Input variables determine the input parameters of a program. They are available from the Properties
window of a program.

There is another way to set how your input parameter will look like in the Inputs tab. For this, place a
string comment after the description of an input parameter in the same line. In this way you can make
names of input parameters more understandable for users.
Example:
//--- input parameters
input int

InpMAPeriod=13;

// Smoothing period

input int

InpMAShift=0;

// Line horizontal shift

input ENUM_MA_METHOD InpMAMethod=MODE_SMMA;

// Smoothing method

2000-2016, MetaQuotes Software Corp.

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.

Passing Parameters When Calling Custom Indicators from MQL5 Programs


Custom Indicators are called using the iCustom() function. After the name of the custom indicator,
parameters should go in a strict accordance with the declaration of input variables of this custom
indicator. If indicated parameters are less than input variables declared in the called custom indicator,
the missing parameters are filled with values specified during the declaration of variables.
If the custom indicator uses the OnCalculate function of the first type (i.e., the indicator is calculated
using the same array of data), then one of ENUM_APPLIED_PRICE values or handle of another indicator
should be used as the last parameter when calling such a custom indicator. All parameters
corresponding to input variables must be clearly indicated.

Enumerations as input Parameters


Not only built-in enumerations provided in MQL5, but also user defined variables can be used as input
variables (input parameters for mql5 programs). For example, we can create the dayOfWeek
enumeration, describing days of the week, and use the input variable to specify a particular day of the
week, not as a number, but in a more common way.
Example:
#property script_show_inputs
//--- day of week
enum dayOfWeek
{
S=0,

// Sunday

M=1,

// Monday

T=2,

// Tuesday

W=3,

// Wednesday

Th=4,

// Thursday

2000-2016, MetaQuotes Software Corp.

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.

Variables with sinput Modifier


Variables with input modifier allow not only setting external parameters values when launching
programs but are also necessary when optimizing trading strategies in the Strategy Tester. Each input
variable excluding the one of a string type can be used in optimization.
Sometimes, it is necessary to exclude some external program parameters from the area of all passes
in the tester. sinput memory modifier has been introduced for such cases. sinput stands for static
external variable declaration (sinput = static input). It means that the following declaration in an
Expert Advisor code

2000-2016, MetaQuotes Software Corp.

185

Language Basics
sinput

int layers=6;

// Number of layers

will be equivalent to the full declaration


static input int layers=6;

// Number of layers

The variable declared with sinput modifier is an input parameter of MQL5 program. The value of this
parameter can be changed when launching the program. However, this variable is not used in the
optimization of input parameters. In other words, its values are not enumerated when searching for
the best set of parameters fitting a specified condition.

The Expert Advisor shown above has 5 external parameters. "Number of layers" is declared to be
sinput and equal to 6. This parameter cannot be changed during a trading strategy optimization. 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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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[]

= { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 };

int

a[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4 } };

//--- from tetris


int

right[4]={WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER,
WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER};

//--- initialization of all fields of the structure with zero values


MqlTradeRequest request={0};

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

189

Language Basics

Visibility Scope and Lifetime of Variables


There are two basic types of scope: local scope and global scope.
A variable declared outside all functions is located into the global scope. Access to such variables can
be done from anywhere in the program.These variables are located in the global pool of memory, so
their lifetime coincides with the lifetime of the program.
A variable declared inside a block (part of code enclosed in curly brackets) belongs to the local scope.
Such a variable is not visible (and therefore not available) outside the block, in which it is declared.
The most common case of local declaration is a variable declared within a function. A variable declared
locally, is located on the stack, and the lifetime of such a variable is equal to the lifetime of the
function.
Since the scope of a local variable is the block in which it is declared, it is possible to declare variables
with the same name, as those of variables declared in other blocks; as well as of those declared at
upper levels, up to the global level.
Example:
void CalculateLWMA(int rates_total,int prev_calculated,int begin,const double &price[])
{
int

i,limit;

static int weightsum=0;


double

sum=0;

//--if(prev_calculated==0)
{
limit=MA_Period+begin;
//--- set empty value for first limit bars
for(i=0; i<limit; i++) LineBuffer[i]=0.0;
//--- calculate first visible value
double firstValue=0;
for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}
firstValue/=(double)weightsum;
LineBuffer[limit-1]=firstValue;
}
else
{
limit=prev_calculated-1;
}
for(i=limit;i<rates_total;i++)
{
sum=0;

2000-2016, MetaQuotes Software Corp.

190

Language Basics
for(int j=0; j<MA_Period; j++) sum+=(MA_Period-j)*price[i-j];
LineBuffer[i]=sum/weightsum;
}
//--}

Pay attention to the variable i, declared in line


for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}

Its scope is only the for loop; outside of this loop there is another variable with the same name,
declared at the beginning of the function. In addition, the k variable is declared in the loop body, its
scope is the loop body.
Local variables can be declared with the access specifier static. In this case, the compiler has a
variable in the global pool of memory. Therefore, the lifetime of a static variable is equal to the
lifetime of the program. Here the scope of such a variable is limited to the block in which it is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Creating and
Deleting Objects

2000-2016, MetaQuotes Software Corp.

191

Language Basics

Creating and Deleting Objects


After a MQL5 program is loaded for execution, memory is allocated to each variable according to its
type. According to the access level, all variables are divided into two types - global variables and local
variables. According to the memory class, they can be input parameters of a MQL5 program, static and
automatic. If necessary, each variable is initialized by a corresponding value. After being used a
variable is unintialized and memory used by it is returned to the MQL5 executable system.

Initialization and Deinitialization of Global Variables


Global variables are initialized automatically right after a MQL5 program is loaded and before any of
function is called. During initialization initial values are assigned to variables of simple types and a
constructor (if there is any) is called for objects. Input variables are always declared at a global level,
and are initialized by values set by a user in the dialog during the program start.
Despite the fact that static variables are usually declared at a local level, the memory for these
variables is pre-allocated, and initialization is performed right after a program is loaded, the same as
for global variables.
The initialization order corresponds to the variable declaration order in the program. Deinitialization is
performed in the reverse order. This rule is true only for the variables that were not created by the
new operator. Such variables are created and initialized automatically right after loading, and are
deinitialized before the program unloading.

Initialization and Deinitialization of Local Variables


If a variable declared on a local level is not a static one, memory is allocated automatically for such a
variable. Local variables, as well as global ones, are initialized automatically at the moment when the
program execution meets their declaration. Thus the initialization order corresponds to the order of
declaration.
Local variables are deinitialized at the end of the program block, in which they were declared, and in
the order opposite to their declaration. A program block is a compound operator that can be a part of
selection operator switch, loop operator (for, while, do-while), a function body or a part of the if-else
operator.
Local variables are initialized only at the moment when the program execution meets the variable
declaration. If during the program execution the block, in which the variable is declared, was not
executed, such a variable is not initialized.

Initialization and Deinitialization of Objects Placed


A special case is that with object pointers, because declaration of a pointer does not entail
initialization of a corresponding objects. Dynamically placed objects are initialized only at the moment
when the class sample is created by the new operator. Initialization of objects presupposes call of a
constructor of a corresponding class. If there is no corresponding constructor in the class, its members
of a simple type will not be automatically initialized; members of types string, dynamic array and
complex object will be automatically initialized.
Pointers can be declared on a local or global level; and they can be initialized by the empty value of
NULL or by the value of the pointer of the same or inherited type. If the new operator is called for a

2000-2016, MetaQuotes Software Corp.

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.

Dynamic memory allocation in MQL5


When working with dynamic arrays, released memory is immediately returned back to the operating
system.
When working with dynamic class objects using the new operator, first memory is requested from the
class memory pool the memory manager is working with. If there is not enough memory in the pool,
memory is requested from the operating system. When deleting the dynamic object using the delete
operator, released memory is immediately returned back to the class memory pool.
Memory manager releases memory back to the operating system immediately after exiting the
following event handling functions: OnInit(), OnDeinit(), OnStart(), OnTick(), OnCalculate(),
OnTimer(),
OnTrade(),
OnTester(),
OnTesterInit(),
OnTesterPass(),
OnTesterDeinit(),
OnChartEvent(), OnBookEvent().

Brief Characteristics of Variables


The main information about the order of creation, deletion, about calls of constructors and destructors
is given in the below table.
Global automatic
variable

Local automatic
variable

Dynamically created
object

Initialization

right after a mql5


program is loaded

when the code line


where it is declared is
reached
during
execution

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

before a mql5 program


is unloaded

when execution exits


the declaration block

when
the
delete
operator is executed
or before a mql5

of

2000-2016, MetaQuotes Software Corp.

193

Language Basics

program is unloaded
Deinitialization
order

in the order opposite


to the initialization
order

in the order opposite


to the initialization
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

when exiting the block


where the variable
was initialized

at the execution of
the delete operator

Error logs

log message in the


"Experts"
journal
about the attempt to
delete
an
automatically created
object

log message in the


"Experts"
journal
about the attempt to
delete
an
automatically created
object

log message in the


"Experts"
journal
about
undeleted
dynamically
created
objects at the unload
of a mql5 program

See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

195

Language Basics

Macro substitution (#define)


The #define directive can be used to assign mnemonic names to constants. There are two forms:
#define identifier expression

// parameter-free form

#define identifier(par1,... par8) expression

// parametric form

The #define directive substitutes expression for all further found entries of identifier in the source
text. The identifier is replaced only if it is a separate token. The identifier is not replaced if it is part
of a comment, part of a string, or part of another longer identifier.
The constant identifier is governed by the same rules as variable names. The value can be of any type:
#define ABC

100

#define PI

3.14

#define COMPANY_NAME

"MetaQuotes Software Corp."

...
void ShowCopyright()
{
Print("Copyright

2001-2009, ",COMPANY_NAME);

Print("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

#define INCOMPLETE TWO+THREE


#define COMPLETE

(TWO+THREE)

void OnStart()
{
Print("2 + 3*2 = ",INCOMPLETE*2);
Print("(2 + 3)*2 = ",COMPLETE*2);
}
// Result
// 2 + 3*2 = 8
// (2 + 3)*2 = 10

Parametric Form #define


With the parametric form, all the subsequent found entries of identifier will be replaced by expression
taking into account the actual parameters. For example:
// example with two parameters a and b
#define A 2+3
#define B 5-1
#define MUL(a, b) ((a)*(b))

2000-2016, MetaQuotes Software Corp.

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

When using the parametric form, maximum 8 parameters are allowed.


// correct parametric form
#define LOG(text)

Print(__FILE__,"(",__LINE__,") :",text)

// one parameter - 'text'

// incorrect parametric form


#define WRONG_DEF(p1, p2, p3, p4, p5, p6, p7, p8, p9)

p1+p2+p3+p4 // more than 8 parameters from

The #undef directive


The #undef directive cancels declaration of the macro substitution, defined before.
Example:
#define MACRO
void func1()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

198

Language Basics

Program Properties (#property)


Every mql5-program allows to specify additional specific parameters named #property that help client
terminal in proper servicing for programs without the necessity to launch them explicitly. This
concerns external settings of indicators, first of all. Properties described in included files are
completely ignored. Properties must be specified in the main mq5-file.
#property identifier value

The compiler will write declared values in the configuration of the module executed.
Constant

Type

Description

icon

string

Path to the file of an image


that will be used as an icon of
the EX5
program.
Path
specification rules are the
same as for resources. The
property must be specified in
the main module with the
MQL5 source code. The icon
file must be in the ICO format.

link

string

Link to the company website

copyright

string

The company name

version

string

Program version, maximum 31


characters

description

string

Brief text description of a


mql5-program.
Several
description can be present,
each of them describes one
line of the text. The total
length of all description can
not exceed 511 characters
including line feed.

stacksize

int

MQL5 program stack size. The


stack of sufficient size is
necessary when executing
function recursive calls.
When launching a script or an
Expert Advisor on the chart,
the stack of at least 8 MB is
allocated.
In
case
of
indicators, the stack size is
always fixed and equal to 1
MB.
When a program is launched in
the strategy tester, the stack
of 16 MB is always allocated

2000-2016, MetaQuotes Software Corp.

199

Language Basics

for it.
library

indicator_applied_price

A library; no start function is


assigned, functions with the
export modifier can be
imported in other mql5programs
int

Specifies the default value for


the "Apply to" field. You can
specify one of the values of
ENUM_APPLIED_PRICE. If the
property is not specified, the
default value is PRICE_CLOSE

indicator_chart_window

Show the indicator in the chart


window

indicator_separate_window

Show the indicator


separate window

in

indicator_height

int

Fixed height of the indicator


subwindow in pixels (property
INDICATOR_HEIGHT)

indicator_buffers

int

Number
of
buffers
indicator calculation

indicator_plots

int

Number of graphic series in


the indicator

indicator_minimum

double

The bottom scaling limit for a


separate indicator window

indicator_maximum

double

The top scaling limit for a


separate indicator window

indicator_labelN

string

Sets a label for the N-th


graphic series displayed in
DataWindow.
For
graphic
series
requiring
multiple
indicator
buffers
(DRAW_CANDLES,
DRAW_FILLING and others),
the label names are defined
using the separator ';'.

indicator_colorN

color

The color for displaying line N,


where N is the number of
graphic series; numbering
starts from 1

indicator_widthN

int

Line thickness in graphic


series, where N is the number
of graphic series; numbering
starts from 1

2000-2016, MetaQuotes Software Corp.

for

200

Language Basics

indicator_styleN

int

Line style in graphic series,


specified by the values of
ENUM_LINE_STYLE. N is the
number of graphic series;
numbering starts from 1

indicator_typeN

int

Type of graphical plotting,


specified by the values of
ENUM_DRAW_TYPE. N is the
number of graphic series;
numbering starts from 1

indicator_levelN

double

Horizontal level of N in a
separate indicator window

indicator_levelcolor

color

Color of horizontal levels of


the indicator

indicator_levelwidth

int

Thickness of horizontal levels


of the indicator

indicator_levelstyle

int

Style of horizontal levels of the


indicator

script_show_confirm

Display a confirmation window


before running the script

script_show_inputs

Display a window with the


properties before running the
script
and
disable
this
confirmation window

tester_indicator

string

Name of a custom indicator in


the
format
of
"indicator_name.ex5".
Indicators that require testing
are defined automatically from
the call of the iCustom()
function, if the corresponding
parameter is set through a
constant string. For all other
cases
(use
of
the
IndicatorCreate() function or
use of a non-constant string in
the parameter that sets the
indicator name) this property
is required

tester_file

string

File name for a tester with the


indication of extension, in
double quotes (as a constant
string). The specified file will
be passed to tester. Input files
to be tested, if there are

2000-2016, MetaQuotes Software Corp.

201

Language Basics

necessary ones, must always


be specified.
tester_library

string

Library
name
with
the
extension, in double quotes. A
library can have 'dll' or 'ex5' as
file extension. Libraries that
require testing are defined
automatically. However, if any
of libraries is used by a custom
indicator, this property is
required

Sample Task of Description and Version Number


#property version

"3.70"

// Current version of the Expert Advisor

#property description "ZigZag universal with Pesavento Patterns"

#property description "At the moment in the indicator several ZigZags with different algorithms are

#property description "It is possible to embed a large number of other indicators showing the highs

#property description "lows and automatically build from these highs and lows various graphical too

Examples of Specifying a Separate Label for Each Indicator Buffer ( "C open; C high; C low; C
close")
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots

#property indicator_type1

DRAW_CANDLES

#property indicator_width1

#property indicator_label1

"C open;C high;C low;C close"

2000-2016, MetaQuotes Software Corp.

202

Language Basics

2000-2016, MetaQuotes Software Corp.

203

Language Basics

Including Files (#include)


The #include command line can be placed anywhere in the program, but usually all inclusions are placed
at the beginning of the source code. Call format:
#include <file_name>
#include "file_name"

Examples:
#include <WinUser32.mqh>
#include "mylib.mqh"

The preprocessor replaces the line #include <file_name> with the content of the file 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

2000-2016, MetaQuotes Software Corp.

204

Language Basics

Importing Function (#import)


Functions are imported from compiled MQL5 modules (*.ex5 files) and from operating system modules
(*.dll files). The module name is specified in the #import directive. For compiler to be able to correctly
form the imported function call and organize proper transmission parameters, the full description of
functions is needed. Function descriptions immediately follow the #import "module name" directive.
New command #import (can be without parameters) completes the block of imported function
descriptions.
#import "file_name"
func1 define;
func2 define;
...
funcN define;
#import

Imported functions can have any names. Functions having the same names but from different modules
can be imported at the same time. Imported functions can have names that coincide with the names
of built-in functions. Operation of scope resolution defines which of the functions should be called.
The order of searching for a file specified after the #import keyword is described in Call of Imported
Functions.
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

MessageBoxW(uint hWnd,string lpText,string lpCaption,uint uType);

#import "stdlib.ex5"
string ErrorDescription(int error_code);
int

RGB(int red_value,int green_value,int blue_value);

bool

CompareDoubles(double number1,double number2);

string DoubleToStrMorePrecision(double number,int precision);


string IntegerToHexString(int integer_number);
#import "ExpertSample.dll"
int

GetIntValue(int);

double GetDoubleValue(double);
string GetStringValue(string);
double GetArrayItemValue(double &arr[],int,int);
bool

SetArrayItemValue(double &arr[],int,int,double);

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

206

Language Basics

Conditional Compilation (#ifdef, #ifndef, #else, #endif)


Preprocessor conditional compilation directives allow compiling or skipping a part of the program
depending on the fulfillment of a certain condition.
That condition can take one of the following forms.
#ifdef identifier

// the code located here is compiled if the identifier has already been defined for the preproce
#endif
#ifndef identifier

// the code located here is compiled if the identifier is not currently defined by #define prepr
#endif

Any of the conditional compilation directives can be followed by any number of lines possibly
containing #else directive and ending with #endif. If the verified condition is true, the lines between
#else and #endif are ignored. If the verified condition is not fulfilled, all lines between 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()
{

2000-2016, MetaQuotes Software Corp.

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
}

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

210

Language Basics

Encapsulation and Extensibility of Types


OOP is a balanced approach to writing software. Data and behavior are packed together. This
encapsulation creates user-defined data types, extending the language data types and interacting with
them. Types extensibility is an opportunity to add to the language user-defined data types, which are
also easy to use, as well as basic types.
An abstract data type, for example, a string, is a description of the ideal, well known behavior type.
The string user knows that the string operations, such as concatenation or print, have a certain
behavior. Concatenation and print operations are called methods.
A certain implementation of ADT may have some restrictions, for example, strings can be limited in
length. These limitations affect the behavior opened to all. At the same time, internal or private
implementation details do not affect directly the way the user sees the object. For example, the string
is often implemented as an array, while the internal base address of this array and its name are not
essential for the user.
Encapsulation is the ability to hide the implementation details when the open interfaces to userdefined type is provided. In MQL5, as well as in C++, class and structure definitions (class and struct)
are used for the encapsulation provisions in combination with access keywords private, protected and
public.
The public keyword shows that access to the members that stand behind it is open without
restrictions. Without this keyword, class members are locked by default. Private members are
accessible only by member functions only of its class.
Protected class functions are available to class functions not only in its class, but also in its inheritor
classes. Public class functions are available for any function within the scope of the class declaration.
The protection makes possible to hide part of the class implementation, thus preventing unexpected
changes in the structure of data. Access restriction or data hiding is a feature of the object-oriented
programming.
Usually, class functions are protected and declared with the protected modifier, the reading and
writing of the values are performed by using special so-called set-and get-methods that are defined by
the public access modifier.

Example:
class CPerson
{
protected:
string

m_name;

// name

public:
void

SetName(string n){m_name=n;}// sets name

string

GetName(){return (m_name);} // returns name

};

This approach offers several advantages. First, by function name we can understand what it does -

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

212

Language Basics
Data Types

2000-2016, MetaQuotes Software Corp.

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;

// X - coordinate of the base point

int

m_ypos;

// Y - coordinate of the base point

public:
CShape(){m_type=0; m_xpos=0; m_ypos=0;} // constructor
void

SetXPos(int x){m_xpos=x;} // set X

void

SetYPos(int y){m_ypos=y;} // set Y

};

Next, create new classes derived from the base class, in which we will add necessary fields, each
specifying a certain class. For the Circle shape it is necessary to add a member that contains the
radius value. The Square shape is characterized by the side value. Therefore, derived classes,
inherited from the base class CShape will be declared as follows:

2000-2016, MetaQuotes Software Corp.

214

Language Basics
//--- The derived class circle
class CCircle : public CShape
{

// After a colon we define the base class


// from which inheritance is made

private:
int

m_radius;

// circle radius

public:
CCircle(){m_type=1;}// constructor, type 1
};

For the Square shape class declaration is similar:


//--- the derived class Square
class CSquare : public CShape
{

// After a colon we define the base class


// from which inheritance is made

private:
int

m_square_side;

// square side

public:
CSquare(){m_type=2;} // constructor, type 2
};

It should be noted that while object is created the base class constructor is called first, and then the
constructor of the derived class is called. 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

2000-2016, MetaQuotes Software Corp.

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 private member is not available from derived classes


m_member;

//--- The protected method is available from the base class and its derived cl
Member(){return(m_member);}

public:

//--- Class constructor is available to all members of classes

private:

//--- A private method for assigning a value to m_member

CBaseClass(){m_member=5;return;};
void

Member(int value) { m_member=value;};

};
//+------------------------------------------------------------------+
//| Derived class with errors

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

class CDerived: public CBaseClass // specification of public inheritance can be omitted, since it i
{
public:
void Func() // In the derived class, define a function with calls to base class members
{
//--- An attempt to modify a private member of the base class
m_member=0;

// Error, the private member of the base class is not available

Member(0);

// Error, the private method of the base class is not available in derived

//--- Reading the member of the base class


Print(m_member);

// Error, the private member of the base class is not available

2000-2016, MetaQuotes Software Corp.

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:

//--- The private member is not available from derived classes


m_Pi;
//--- Getting and setting a value for m_Pi

void

SetPI(double v){m_Pi=v;return;};

double

GetPI(){return m_Pi;};

public:

// The class constructor is available to all members


CBaseMathClass() {SetPI(3.14);

PrintFormat("%s",__FUNCTION__);};

};
//+------------------------------------------------------------------+
//| Derived class, in which m_Pi cannot be modified

//+------------------------------------------------------------------+
class CProtectedChildClass: protected CBaseMathClass // Protected inheritance
{
private:
double
public:

m_radius;
//--- Public methods in the derived class

void

SetRadius(double r){m_radius=r; return;};

double

GetCircleLength(){return GetPI()*m_radius;};

};
//+------------------------------------------------------------------+
//| Script starting function

//+------------------------------------------------------------------+
void OnStart()
{

//--- When creating a derived class, the constructor of the base class will be called automatically
CProtectedChildClass pt;
//--- Specify radius
pt.SetRadius(10);
PrintFormat("Length=%G",pt.GetCircleLength());

//--- If we uncomment the line below, we will get an error at the stage of compilation, since SetPI
// pt.SetPI(3);

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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;

// X - coordinate of the base point

int

m_ypos;

// Y - coordinate of the base point

void

CShape(){m_type=0;};

// constructor, type=0

int

GetType(){return(m_type);};// returns type of the shape

public:

virtual
double

GetArea(){return (0); }// returns area of the shape

};

Now, all of the derived classes have a member function getArea(), which returns a zero value. The
implementation of this function in each descendant will vary.
//--- The derived class Circle
class CCircle : public CShape
{

// After a colon we define the base class


// from which inheritance is made

private:
double

m_radius;

// circle radius

void

CCircle(){m_type=1;};

// constructor, type=1

void

SetRadius(double r){m_radius=r;};

public:

virtual double GetArea(){return (3.14*m_radius*m_radius);}// circle area


};

For the class Square the declaration is the same:


//--- The derived class Square
class CSquare : public CShape
{

// After a colon we define the base class


// from which inheritance is made

2000-2016, MetaQuotes Software Corp.

219

Language Basics
private:
double

m_square_side;

// square side

public:
void

CSquare(){m_type=2;}; // constructor, type=1

void

SetSide(double s){m_square_side=s;};

virtual double

GetArea(){return (m_square_side*m_square_side);}// square area

};

For calculating the area of the square and circle, we need the corresponding values of m_radius and
m_square_side, so we have added the functions SetRadius() and SetSide() in the declaration of the
corresponding class.
It is assumed that object of different types (CCircle and CSquare) derived from one base type CShape
are used in our program. Polymorphism allows creating an array of objects of the base CShape class,
but when declaring this array, these objects are yet unknown and their type is undefined.
The decision on what type of object will be contained in each element of the array will be taken
directly during program execution. This involves the dynamic creation of objects of the appropriate
classes, and hence the necessity to use object pointers instead of objects.
The new operator is used for dynamic creation of objects. Each such object must be individually and
explicitly deleted using the delete operator. Therefore we will declare an array of pointers of CShape
type, and create an object of a proper type for each element (new Class_Name), as shown in the
following script example:
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare an array of object pointers of the base type
CShape *shapes[5];

// An array of pointers to CShape object

//--- Here fill in the array with derived objects


//--- Declare a pointer to the object of CCircle type
CCircle *circle=new CCircle();
//--- Set object properties at the circle pointer
circle.SetRadius(2.5);
//--- Place the pointer value in shapes[0]
shapes[0]=circle;
//--- Create another CCircle object and write down its pointer in shapes[1]
circle=new CCircle();
shapes[1]=circle;
circle.SetRadius(5);
//--- Here we intentionally "forget" to set a value for shapes[2]
//circle=new CCircle();
//circle.SetRadius(10);
//shapes[2]=circle;

2000-2016, MetaQuotes Software Corp.

220

Language Basics

//--- Set NULL for the element that is not used


shapes[2]=NULL;
//--- Create a CSquare object and write down its pointer to shapes[3]
CSquare *square=new CSquare();
square.SetSide(5);
shapes[3]=square;
//--- Create a CSquare object and write down its pointer to shapes[4]
square=new CSquare();
square.SetSide(10);
shapes[4]=square;
//--- We have an array of pointers, get its size
int total=ArraySize(shapes);
//--- Pass in a loop through all pointers in the array
for(int i=0; i<5;i++)
{
//--- If the pointer at the specified index is valid
if(CheckPointer(shapes[i])!=POINTER_INVALID)
{
//--- Log the type and square of the shape
PrintFormat("The object of type %d has the square %G",
shapes[i].GetType(),
shapes[i].GetArea());
}
//--- If the pointer has type POINTER_INVALID
else
{
//--- Notify of an error
PrintFormat("Object shapes[%d] has not been initialized! Its pointer is %s",
i,EnumToString(CheckPointer(shapes[i])));
}
}
//--- We must delete all created dynamic objects
for(int i=0;i<total;i++)
{
//--- We can delete only the objects with pointers of POINTER_DYNAMIC type
if(CheckPointer(shapes[i])==POINTER_DYNAMIC)
{
//--- Notify of deletion
PrintFormat("Deleting shapes[%d]",i);
//--- Delete an object by its pointer
delete shapes[i];
}
}
}

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

SetRightBorder(int border) { m_right_border=border; }

void

SetYPos(int ypos)

{ m_ypos=ypos;

void

SetXPos(int xpos)

{ m_xpos=xpos;

int

GetYPos()

{ return(m_ypos);

int

GetXPos()

{ return(m_xpos);

int

GetYSize()

{ return(m_ysize);

int

GetXSize()

{ return(m_xsize);

int

GetType()

{ return(m_type);

void

Left()

{ m_xpos-=SHAPE_SIZE;

void

Right()

{ m_xpos+=SHAPE_SIZE;

void

Rotate()

{ m_prev_turn=m_turn; if(++m_turn>3) m_turn=0; }

virtual void

Draw()

{ return;

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

226

Language Basics

Static members of a Class/Structure


Static Members
The members of a class can be declared using the storage class modifier static. These data members
are shared by all instances of this class and are stored in one place. Non-static data members are
created for each class object variable.
The inability to declare static members of a class would have led to the need to declare these data on
the the global level of the program. It would break the relationship between the data and their class,
and is not consistent with the basic paradigm of the OOP - joining data and methods for handling them
in a class. The static member allows class data that are not specific to a particular instance to exist in
the class scope.
Since a static class member does not depend on the particular instance, the reference to it is as
follows:
class_name::variable

where class_name is the name of the class, and variable is the name of the class member.
As you see, to access the static member of a class, context resolution operator :: is used. 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;

//--- Constructor and destructor


CParser(void);
~CParser(void){};
};
...
//--- Initialization of static members of the Parser class at the global level
int CParser::s_words=0;
int CParser::s_symbols=0;

A static class member can be declared with the const keyword. Such static constants must be
initialized at the global level with the const keyword:

2000-2016, MetaQuotes Software Corp.

227

Language Basics
//+------------------------------------------------------------------+
//| Class "Stack" for storing processed data

//+------------------------------------------------------------------+
class CStack
{
public:
CStack(void);
~CStack(void){};
...
private:
static const int

s_max_length; // Maximum stack capacity

};
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;

Pointer this
The keyword this denotes an implicitly declared pointer to itself to a specific instance of the class, in
the context of which the method is executed. It can be used only in non-static methods of the class.
Pointer this is an implicit non-static member of any class.
In static functions you can access only static members/methods of a class.

Static Methods
In MQL5 member functions of type static can be used. The static modifier must precede the return
type of a function in the declaration inside a class.
class CStack
{
public:
//--- Constructor and destructor
CStack(void){};
~CStack(void){};
//--- Maximum stack capacity
static int

Capacity();

private:
int

m_length;

static const int

s_max_length; // Maximum stack capacity

// The number of elements in the stack

};
//+------------------------------------------------------------------+
//| Returns the maximum number of elements to store in the stack

//+------------------------------------------------------------------+
int CStack::Capacity(void)
{
return(s_max_length);
}
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;

2000-2016, MetaQuotes Software Corp.

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

Square(const double w,const double h);// { return(w*h); }

};
//+------------------------------------------------------------------+
//| Returns the area of the "Rectangle" object

//+------------------------------------------------------------------+
double CRectangle::Square(void) const
{
return(Square(m_width,m_height));
}
//+------------------------------------------------------------------+
//| Returns the product of two variables

//+------------------------------------------------------------------+
static double CRectangle::Square(const double w,const double h)
{

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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[]

// array with int type elements

);

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

2000-2016, MetaQuotes Software Corp.

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

fill with random values

for(int i=0;i<size;i++)
{
array[i]=MathRand();
}
//--- find position of the highest value in the array
int max_position=ArrayMaximum(array);
//--- now, get the highest value itself in the array
double max=array[max_position];
//--- display the found value
Print("Max value = ",max);

Thus, we have performed two steps to get the highest value in the array. 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.

2000-2016, MetaQuotes Software Corp.

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

Print("i_value: type=",GetTypeName(i_value), ",

value=", i_value);

Print("trade: type=",GetTypeName(trade));
//--}
//+------------------------------------------------------------------+
//| Type is returned as a line

//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T &t)
{
//--- return the type as a line
return(typename(T));
//--}

Function templates can also be used for class methods, for example:
class CFile
{
...
public:
...
template<typename T>
uint WriteStruct(T &data);
};
template<typename T>
uint CFile::WriteStruct(T &data)
{
...
return(FileWriteStruct(m_handle,data));
}

2000-2016, MetaQuotes Software Corp.

233

Language Basics

Function templates should not be declared with export, virtual and #import keywords.

2000-2016, MetaQuotes Software Corp.

234

Language Basics

Abstract Classes and Pure Virtual Functions


Abstract classes are used for creating generic entities, that you expect to use for creating more
specific derived classes. An abstract class can only be used as the base class for some other class, that
is why it is impossible to create an object of the abstract class type.
A class which contains at least one pure virtual function in it is abstract. Therefore, classes derived
from the abstract class must implement all its pure virtual functions, otherwise they will also be
abstract classes.
A virtual function is declared as "pure" by using the pure-specifier syntax. Consider the example of the
CAnimal class, which is only created to provide common functions the objects of the CAnimal type
are too general for practical use. Thus, CAnimal is a good example for an abstract class:
class CAnimal
{
public:
virtual void

CAnimal();

// Constructor

Sound() = 0;

// A pure virtual function

m_legs_count;

// The number of the animal's legs

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;

// PURE method, should be overridden in the derived class, CA

};
//--- Derived from an abstract class
class CCat : public CAnimal
{
public:
virtual void

Sound() { Print("Myau"); } // PURE is overridden, CCat is not abstract and ca

};
//--- Examples of wrong use
new CAnimal;

// Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract

CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract
//--- Examples of proper use
new CCat;

// No error - the CCat class is not abstract

CCat cat;

// No error - the CCat class is not abstract

2000-2016, MetaQuotes Software Corp.

235

Language Basics

Restrictions on abstract classes


If the constructor for an abstract class calls a pure virtual function (either directly or indirectly), the
result is undefined.
//+------------------------------------------------------------------+
//| An abstract base class

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

2000-2016, MetaQuotes Software Corp.

236

Standard Constants, Enumerations and Structures

Standard Constants, Enumerations and Structures


To simplify the program writing and to make program texts more convenient for perception, the MQL5
language provides predefined standard constants and enumerations. Besides that, service structures
are used for storing information.
Standard constants are similar to macros and are of int type.
The constants are grouped by their purposes:
Chart constants are used when working with price charts: opening, navigation, setting parameters;
Objects constants are intended for processing graphical objects that can be created and displayed in

charts;
Indicators constants are used for working with standard and custom indicators;
Environment state constants describe properties of a MQL5-program, show information about a

client terminal, financial instrument and current account;


Trade constants allow to specify a variety of information in the course of trading;
Named constants are constants of the MQL5 language;
Data structures describe data storage formats used;
Codes of errors and warnings describe compiler messages and trading server answers to trade

requests;
In/out constants are designed for working with file functions and displaying messages on the screen

by the MessageBox() function.

2000-2016, MetaQuotes Software Corp.

237

Standard Constants, Enumerations and Structures

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.

2000-2016, MetaQuotes Software Corp.

238

Standard Constants, Enumerations and Structures

Types of Chart Events


There are 9 types of events that can be processed using the predefined function OnChartEvent(). For
custom events 65535 identifiers are provided in the range of CHARTEVENT_CUSTOM to
CHARTEVENT_CUSTOM_LAST inclusive. To generate a custom event, the EventChartCustom() function
should be used.
ENUM_CHART_EVENT
ID

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

Graphical object property changed via the


properties dialog

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

Clicking on a graphical object

CHARTEVENT_OBJECT_DRAG

Drag and drop of a graphical object

CHARTEVENT_OBJECT_ENDEDIT

End of text editing in the graphical object Edit

CHARTEVENT_CHART_CHANGE

Change of the chart size or modification of chart


properties through the Properties dialog

CHARTEVENT_CUSTOM

Initial number of an event from a range of


custom events

CHARTEVENT_CUSTOM_LAST

The final number of an event from a range of


custom events

For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through 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

2000-2016, MetaQuotes Software Corp.

Value of
sparam
parameter

the

The string value


of a bit mask

239

Standard Constants, Enumerations and Structures

times
the
keystroke
is
repeated as a
result of the user
holding down the
key)

describing
the
status
of
keyboard buttons

Mouse events (if


CHART_EVENT_
MOUSE_MOVE=tr
ue is set for the
chart)

CHARTEVENT_MO
USE_MOVE

the X coordinate

the Y coordinate

The string value


of a bit mask
describing
the
status of mouse
buttons

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

2000-2016, MetaQuotes Software Corp.

240

Standard Constants, Enumerations and Structures

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

Value set by the


EventChartCusto
m() function

Value set by the


EventChartCusto
m() function

Value set by the


EventChartCusto
m() function

Example:
#define KEY_NUMPAD_5

12

#define KEY_LEFT

37

#define KEY_UP

38

#define KEY_RIGHT

39

#define KEY_DOWN

40

#define KEY_NUMLOCK_DOWN

98

#define KEY_NUMLOCK_LEFT

100

#define KEY_NUMLOCK_5

101

#define KEY_NUMLOCK_RIGHT 102


#define KEY_NUMLOCK_UP

104

//+------------------------------------------------------------------+
//| Expert initialization function

//+------------------------------------------------------------------+
int OnInit()
{
//--Print("The expert with name ",MQL5InfoString(MQL5_PROGRAM_NAME)," is running");
//--- 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

const double& dparam, // Event parameter of double type


const string& sparam

// Event parameter of string type

)
{
//--- the left mouse button has been pressed on the chart

2000-2016, MetaQuotes Software Corp.

241

Standard Constants, Enumerations and Structures


if(id==CHARTEVENT_CLICK)
{
Print("The coordinates of the mouse click on the chart are: x = ",lparam,"

y = ",dparam);

}
//--- the mouse has been clicked on the graphic object
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("The mouse has been clicked on the object with name '"+sparam+"'");
}
//--- the key has been pressed
if(id==CHARTEVENT_KEYDOWN)
{
switch(lparam)
{
case KEY_NUMLOCK_LEFT:

Print("The KEY_NUMLOCK_LEFT has been pressed");

break;

case KEY_LEFT:

Print("The KEY_LEFT has been pressed");

break;

case KEY_NUMLOCK_UP:

Print("The KEY_NUMLOCK_UP has been pressed");

break;

case KEY_UP:

Print("The KEY_UP has been pressed");

break;

case KEY_NUMLOCK_RIGHT: Print("The KEY_NUMLOCK_RIGHT has been pressed");

break;

case KEY_RIGHT:

Print("The KEY_RIGHT has been pressed");

break;

case KEY_NUMLOCK_DOWN:

Print("The KEY_NUMLOCK_DOWN has been pressed");

break;

case KEY_DOWN:

Print("The KEY_DOWN has been pressed");

break;

case KEY_NUMPAD_5:

Print("The KEY_NUMPAD_5 has been pressed");

break;

case KEY_NUMLOCK_5:

Print("The KEY_NUMLOCK_5 has been pressed");

break;

default:

Print("Some not listed key has been pressed");

}
ChartRedraw();
}
//--- the object has been deleted
if(id==CHARTEVENT_OBJECT_DELETE)
{
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");
}
}

2000-2016, MetaQuotes Software Corp.

242

Standard Constants, Enumerations and Structures


For CHARTEVENT_MOUSE_MOVE event the sparam string parameter contains information about state
of the keyboard and mouse buttons:
Bit

Description
1

State of the left mouse button

State of the right mouse button

State of the SHIFT button

State of the CTRL button

State of the middle mouse button

State of the first extra mouse button

State of the second extra mouse button

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

+(((state& 1)== 1)?"DN":"UP");

// mouse left

res+="\nMR: "

+(((state& 2)== 2)?"DN":"UP");

// mouse right

res+="\nMM: "

+(((state&16)==16)?"DN":"UP");

// mouse middle

res+="\nMX: "

+(((state&32)==32)?"DN":"UP");

// mouse first X key

res+="\nMY: "

+(((state&64)==64)?"DN":"UP");

// mouse second X key

res+="\nSHIFT: "+(((state& 4)== 4)?"DN":"UP");

// shift key

res+="\nCTRL: " +(((state& 8)== 8)?"DN":"UP");

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

2000-2016, MetaQuotes Software Corp.

243

Standard Constants, Enumerations and Structures

See also
Event Handling Functions, Working with events

2000-2016, MetaQuotes Software Corp.

244

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

245

Standard Constants, Enumerations and Structures


//--- Define symbol
ObjectSetString(0,chart_name,OBJPROP_SYMBOL,"EURUSD");
//--- Set X coordinate of the anchor point
ObjectSetInteger(0,chart_name,OBJPROP_XDISTANCE,100);
//--- Set Y coordinate of the anchor point
ObjectSetInteger(0,chart_name,OBJPROP_YDISTANCE,100);
//--- Set the width of chart
ObjectSetInteger(0,chart_name,OBJPROP_XSIZE,400);
//--- Set the height
ObjectSetInteger(0,chart_name,OBJPROP_YSIZE,300);
//--- Set the timeframe
ObjectSetInteger(0,chart_name,OBJPROP_PERIOD,PERIOD_D1);
//--- Set scale (from 0 to 5)
ObjectSetDouble(0,chart_name,OBJPROP_SCALE,4);
//--- Disable selection by a mouse
ObjectSetInteger(0,chart_name,OBJPROP_SELECTABLE,false);

See also
PeriodSeconds, Period, Date and Time, Visibility of objects

2000-2016, MetaQuotes Software Corp.

246

Standard Constants, Enumerations and Structures

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

Show chart on top of other


charts

bool w/o

CHART_MOUSE_SCROLL

Scrolling the chart horizontally


using the left mouse button.
Vertical scrolling
is
also
available if the value of any
following properties is set to
true:
CHART_SCALEFIX,
CHART_SCALEFIX_11
or
CHART_SCALE_PT_PER_BAR

bool

CHART_EVENT_MOUSE_MOVE

Send notifications of mouse


move and mouse click events
(CHARTEVENT_MOUSE_MOVE)
to all mql5 programs on a chart

bool

CHART_EVENT_OBJECT_CREAT
E

Send a notification of an event


of
new
object
creation
(CHARTEVENT_OBJECT_CREAT
E) to all mql5-programs on a
chart

bool

CHART_EVENT_OBJECT_DELET

Send a notification of an event

bool

2000-2016, MetaQuotes Software Corp.

247

Standard Constants, Enumerations and Structures

of
object
deletion
(CHARTEVENT_OBJECT_DELETE
) to all mql5-programs on a
chart

CHART_MODE

Chart type (candlesticks, bars


or line)

enum

CHART_FOREGROUND

Price chart in the foreground

bool

CHART_SHIFT

Mode of price chart indent


from the right border

bool

CHART_AUTOSCROLL

Mode of automatic moving to


the right border of the chart

bool

CHART_SCALE

Scale

int

CHART_SCALEFIX

Fixed scale mode

bool

CHART_SCALEFIX_11

Scale 1:1 mode

bool

CHART_SCALE_PT_PER_BAR

Scale to be specified in points


per bar

bool

CHART_SHOW_OHLC

Show OHLC values in the upper


left corner

bool

CHART_SHOW_BID_LINE

Display Bid values as


horizontal line in a chart

bool

CHART_SHOW_ASK_LINE

Display Ask values as


horizontal line in a chart

bool

CHART_SHOW_LAST_LINE

Display Last values as


horizontal line in a chart

bool

CHART_SHOW_PERIOD_SEP

Display vertical separators


between adjacent periods

bool

CHART_SHOW_GRID

Display grid in the chart

bool

CHART_SHOW_VOLUMES

Display volume in the chart

enum
ENUM_CHART_VOLUME_MODE

CHART_SHOW_OBJECT_DESCR

Display textual descriptions of


objects (not available for all
objects)

bool

CHART_VISIBLE_BARS

The number of bars on the


chart that can be displayed

int r/o

CHART_WINDOWS_TOTAL

The total number of chart


windows, including indicator
subwindows

int r/o

CHART_WINDOW_IS_VISIBLE

Visibility of subwindows

bool r/o modifier - subwindow


number

2000-2016, MetaQuotes Software Corp.

ENUM_CHART_MODE

from 0 to 5

248

Standard Constants, Enumerations and Structures

CHART_WINDOW_HANDLE

Chart window handle (HWND)

int r/o

CHART_WINDOW_YDISTANCE

The distance between the


upper frame of the indicator
subwindow and the upper
frame of the main chart
window, along the vertical Y
axis, in pixels. In case of a
mouse event, the cursor
coordinates are passed in
terms of the coordinates of the
main chart window, while the
coordinates
of
graphical
objects
in
an
indicator
subwindow are set relative to
the upper left corner of the
subwindow.
The value is required for
converting
the
absolute
coordinates of the main chart
to the local coordinates of a
subwindow for correct work
with the graphical objects,
whose coordinates are set
relative to
the upper left
corner of the subwindow
frame.

int r/o
number

CHART_FIRST_VISIBLE_BAR

Number of the first visible bar


in the chart. Indexing of bars is
the same as for timeseries.

int r/o

CHART_WIDTH_IN_BARS

Chart width in bars

int r/o

CHART_WIDTH_IN_PIXELS

Chart width in pixels

int r/o

CHART_HEIGHT_IN_PIXELS

Chart height in pixels

int
modifier - subwindow
number

CHART_COLOR_BACKGROUND

Chart background color

color

CHART_COLOR_FOREGROUND

Color of axes, scales and OHLC


line

color

CHART_COLOR_GRID

Grid color

color

CHART_COLOR_VOLUME

Color of volumes and position


opening levels

color

CHART_COLOR_CHART_UP

Color for the up bar, shadows


and body borders of bull
candlesticks

color

CHART_COLOR_CHART_DOWN

Color for the down bar,


shadows and body borders of

color

2000-2016, MetaQuotes Software Corp.

modifier - subwindow

249

Standard Constants, Enumerations and Structures

bear candlesticks
CHART_COLOR_CHART_LINE

Line chart color and color of


"Doji" Japanese candlesticks

color

CHART_COLOR_CANDLE_BULL

Body color of a bull candlestick

color

CHART_COLOR_CANDLE_BEAR

Body color of a bear candlestick

color

CHART_COLOR_BID

Bid price level color

color

CHART_COLOR_ASK

Ask price level color

color

CHART_COLOR_LAST

Line color of the last executed


deal price (Last)

color

CHART_COLOR_STOP_LEVEL

Color of stop order levels (Stop


Loss and Take Profit)

color

CHART_SHOW_TRADE_LEVELS

Displaying trade levels in the


chart (levels of open positions,
Stop Loss, Take Profit and
pending orders)

bool

CHART_DRAG_TRADE_LEVELS

Permission to drag trading


levels on a chart with a mouse.
The drag mode is enabled by
default (true value)

bool

CHART_SHOW_DATE_SCALE

Showing the time scale on a


chart

bool

CHART_SHOW_PRICE_SCALE

Showing the price scale on a


chart

bool

CHART_SHOW_ONE_CLICK

Showing the "One click trading"


panel on a chart

bool

For functions ChartSetDouble() and ChartGetDouble()


ENUM_CHART_PROPERTY_DOUBLE
ID

Description

Property Type

CHART_SHIFT_SIZE

The size of the zero bar indent


from the right border in
percents

double
(from
percents)

CHART_FIXED_POSITION

Chart fixed position from the


left border in percent value.
Chart fixed position is marked
by a small gray triangle on the
horizontal time axis. It is
displayed only if the automatic
chart scrolling to the right on
tick incoming is disabled (see
CHART_AUTOSCROLL

double

2000-2016, MetaQuotes Software Corp.

10

to

50

250

Standard Constants, Enumerations and Structures


property). The bar on a fixed
position remains in the same
place when zooming in and out.
CHART_FIXED_MAX

Fixed chart maximum

double

CHART_FIXED_MIN

Fixed chart minimum

double

CHART_POINTS_PER_BAR

Scale in 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

For functions ChartSetString() and ChartGetString()


ENUM_CHART_PROPERTY_STRING
ID

Description

CHART_COMMENT

Property Type

Text of a comment in a chart

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

2000-2016, MetaQuotes Software Corp.

251

Standard Constants, Enumerations and Structures


}
}

See also
Examples of Working with the Chart

2000-2016, MetaQuotes Software Corp.

252

Standard Constants, Enumerations and Structures

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 beginning (the oldest prices)

CHART_CURRENT_POS

Current position

CHART_END

Chart end (the latest prices)

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

2000-2016, MetaQuotes Software Corp.

253

Standard Constants, Enumerations and Structures

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

Display as a sequence of bars

CHART_CANDLES

Display as Japanese candlesticks

CHART_LINE

Display as a line drawn by Close prices

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

Volumes are not shown

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

2000-2016, MetaQuotes Software Corp.

254

Standard Constants, Enumerations and Structures


}

See also
ChartOpen, ChartID

2000-2016, MetaQuotes Software Corp.

255

Standard Constants, Enumerations and Structures

Examples of Working with the Chart


This section contains examples of working with chart properties. One or two complete functions are
displayed for each property. These functions allow setting/receiving the value of the property. These
functions can be used "as is" in custom mql5 applications.
The screenshot below demonstrates the graphic panel illustrating how changing of the chart property
changes its appearance. Clicking Next button allows setting the new value of the appropriate property
and view the changes in the chart window.

The panel's source code is located below.

Chart Properties and Sample Functions for Working with Them


CHART_IS_OBJECT defines if an object is a real chart or a graphic object.

//+------------------------------------------------------------------+
//| Checks if an object is a chart. If it is a graphic object,

//| the result is true. If it is a real chart, the result variable

//| has the value of false.

//+------------------------------------------------------------------+
bool ChartIsObject(bool &result,const long chart_ID=0)
{

2000-2016, MetaQuotes Software Corp.

256

Standard Constants, Enumerations and Structures


//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- get the chart property
if(!ChartGetInteger(chart_ID,CHART_IS_OBJECT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
//--- return false
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}

CHART_BRING_TO_TOP shows the chart on top of all others.

//+----------------------------------------------------------------------+
//| 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)
{

2000-2016, MetaQuotes Software Corp.

257

Standard Constants, Enumerations and Structures


//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MOUSE_SCROLL,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 scrolling of chart using left mouse button

//+--------------------------------------------------------------------+
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

is a property of sending messages concerning move events and


mouse clicks to mql5 applications (CHARTEVENT_MOUSE_MOVE).

//+------------------------------------------------------------------+
//| Checks if messages concerning move events and mouse clicks

//| are sent to all MQL5 applications on the chart

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

258

Standard Constants, Enumerations and Structures


if(!ChartGetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,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 mode of sending messages concerning move events and

//| mouse clicks to MQL5 applications on the chart

//+------------------------------------------------------------------------------+
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);
}

CHART_EVENT_OBJECT_CREATE is a property of sending messages concerning the event of a

graphic object creation to mql5 applications (CHARTEVENT_OBJECT_CREATE).


//+---------------------------------------------------------------------+
//| Checks if messages concerning the event of a graphic

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

2000-2016, MetaQuotes Software Corp.

259

Standard Constants, Enumerations and Structures


return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Enables/disables the mode of sending messages concerning the event of a

//| graphic object creation to all mql5 applications on the chart

//+--------------------------------------------------------------------------+
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);
}

CHART_EVENT_OBJECT_DELETE is a property of sending messages concerning the event of a

graphic object deletion to mql5 applications (CHARTEVENT_OBJECT_DELETE).


//+---------------------------------------------------------------------+
//| Checks if messages concerning the event of a graphic object

//| deletion are sent to all mql5 applications on the chart

//+---------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

260

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Enables/disables the mode of sending messages concerning the event of a

//| graphic object deletion to all mql5 applications on the chart

//+--------------------------------------------------------------------------+
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);
}

CHART_MODE type of the chart (candlesticks, bars or line).

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

261

Standard Constants, Enumerations and Structures


ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MODE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_FOREGROUND is a property of displaying a price chart in the foreground.

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

2000-2016, MetaQuotes Software Corp.

262

Standard Constants, Enumerations and Structures


}
//--- successful execution
return(true);
}

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

2000-2016, MetaQuotes Software Corp.

263

Standard Constants, Enumerations and Structures


CHART_AUTOSCROLL the mode of automatic shift to the right border of the chart.

//+------------------------------------------------------------------+
//| Checks if automatic scrolling of a chart to the right

//| on new ticks arrival is enabled

//+------------------------------------------------------------------+
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

//| on new ticks arrival

//+------------------------------------------------------------------+
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);
}

CHART_SCALE chart scale property.

2000-2016, MetaQuotes Software Corp.

264

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Gets chart scale (from 0 to 5)

//+------------------------------------------------------------------+
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);
}

CHART_SCALEFIX the mode of fixed chart scale.

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

265

Standard Constants, Enumerations and Structures


if(!ChartGetInteger(chart_ID,CHART_SCALEFIX,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 fixed scale mode

//+------------------------------------------------------------------+
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);
}

CHART_SCALEFIX_11 1:1 chart scale mode.

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

266

Standard Constants, Enumerations and Structures


result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables the "1:1" scale mode

//+------------------------------------------------------------------+
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

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

2000-2016, MetaQuotes Software Corp.

267

Standard Constants, Enumerations and Structures


bool ChartScalePerBarSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

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

2000-2016, MetaQuotes Software Corp.

268

Standard Constants, Enumerations and Structures


//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

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

2000-2016, MetaQuotes Software Corp.

269

Standard Constants, Enumerations and Structures

CHART_SHOW_ASK_LINE the property of displaying Ask value as a horizontal line on a chart.

//+------------------------------------------------------------------+
//| 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);
}

CHART_SHOW_LAST_LINE the property of displaying Last value as a horizontal line on a chart.

//+-----------------------------------------------------------------------------+
//| Checks if displaying of line for the last performed deal's price is enabled |
//+-----------------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

270

Standard Constants, Enumerations and Structures


bool ChartShowLastLineGet(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_LAST_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 line for the last performed deal's price |
//+-------------------------------------------------------------------------+
bool ChartShowLastLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_LAST_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_SHOW_PERIOD_SEP the property of displaying vertical separators between adjacent

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

2000-2016, MetaQuotes Software Corp.

271

Standard Constants, Enumerations and Structures


//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,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 vertical separators between adjacent periods |
//+-----------------------------------------------------------------------------+
bool ChartShowPeriodSepapatorSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_SHOW_GRID the property of displaying the chart grid.

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

272

Standard Constants, Enumerations and Structures


//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of grid on chart

//+------------------------------------------------------------------+
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);
}

CHART_SHOW_VOLUMES the property of displaying the volumes on a chart.

//+------------------------------------------------------------------+
//| Checks if volumes are displayed on a chart

//| The flag indicates the volumes showing mode

//+------------------------------------------------------------------+
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)

2000-2016, MetaQuotes Software Corp.

273

Standard Constants, Enumerations and Structures


{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_VOLUMES,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_SHOW_OBJECT_DESCR the property of graphical object pop-up descriptions.

//+-------------------------------------------------------------------+
//| Checks if pop-up descriptions of graphical objects are displayed

//| when hovering mouse over them

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

2000-2016, MetaQuotes Software Corp.

274

Standard Constants, Enumerations and Structures


//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

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

the total number of chart windows including indicator

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

2000-2016, MetaQuotes Software Corp.

275

Standard Constants, Enumerations and Structures


//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

CHART_WINDOW_IS_VISIBLE defines the subwindow's visibility.

//+------------------------------------------------------------------+
//| 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);
}

CHART_WINDOW_HANDLE returns the chart handle.

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

2000-2016, MetaQuotes Software Corp.

276

Standard Constants, Enumerations and Structures


}
//--- return the value of the chart property
return((int)result);
}

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

//| subwindow and the upper border of chart's main window

//+------------------------------------------------------------------+
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

corresponds to the time series).


//+------------------------------------------------------------------------------+
//| Gets the index of the first visible bar on chart.

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

2000-2016, MetaQuotes Software Corp.

277

Standard Constants, Enumerations and Structures


//--- return the value of the chart property
return((int)result);
}

CHART_WIDTH_IN_BARS returns the chart width in bars.

//+------------------------------------------------------------------+
//| 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);
}

CHART_WIDTH_IN_PIXELS returns the chart width in pixels.

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

278

Standard Constants, Enumerations and Structures


CHART_HEIGHT_IN_PIXELS chart height property in pixels.

//+------------------------------------------------------------------+
//| 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);
}

CHART_COLOR_BACKGROUND - chart background color.

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

279

Standard Constants, Enumerations and Structures


ResetLastError();
//--- receive chart background color
if(!ChartGetInteger(chart_ID,CHART_COLOR_BACKGROUND,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 background color of chart

//+------------------------------------------------------------------+
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);
}

CHART_COLOR_FOREGROUND color of axes, scale and OHLC line.

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

280

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Sets the color of axes, scale and OHLC line

//+------------------------------------------------------------------+
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);
}

CHART_COLOR_GRID chart grid color.

//+------------------------------------------------------------------+
//| 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))
{

2000-2016, MetaQuotes Software Corp.

281

Standard Constants, Enumerations and Structures


//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_COLOR_VOLUME - color of volumes and position opening levels.

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

282

Standard Constants, Enumerations and Structures


CHART_COLOR_CHART_UP color of up bar, its shadow and border of a bullish candlestick's body.

//+-----------------------------------------------------------------------------+
//| 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;

2000-2016, MetaQuotes Software Corp.

283

Standard Constants, Enumerations and Structures


//--- reset the error value
ResetLastError();
//--- receive the color of down bar, its shadow and border of bearish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_DOWN,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 down bar, shadow and border of a bearish candlestick's body |
//+-------------------------------------------------------------------------------+
bool ChartDownColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of down bar, its shadow and border of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_DOWN,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_COLOR_CHART_LINE color of the chart line and Doji candlesticks.

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

2000-2016, MetaQuotes Software Corp.

284

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| Sets the color of chart line and Doji candlesticks

//+------------------------------------------------------------------+
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);
}

CHART_COLOR_CANDLE_BULL color of bullish candlestick's body.

//+------------------------------------------------------------------+
//| 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))

2000-2016, MetaQuotes Software Corp.

285

Standard Constants, Enumerations and Structures


{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_COLOR_CANDLE_BEAR color of bearish candlestick's body.

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

286

Standard Constants, Enumerations and Structures


CHART_COLOR_BID Bid price line color.

//+------------------------------------------------------------------+
//| 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);
}

CHART_COLOR_ASK Ask price line color.

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

287

Standard Constants, Enumerations and Structures


ResetLastError();
//--- receive the color of Ask price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_ASK,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 Ask line

//+------------------------------------------------------------------+
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);
}

CHART_COLOR_LAST color of the last performed deal's price line (Last).

//+------------------------------------------------------------------+
//| 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);
}

2000-2016, MetaQuotes Software Corp.

288

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Sets the color of the last performed deal's price line

//+------------------------------------------------------------------+
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))
{

2000-2016, MetaQuotes Software Corp.

289

Standard Constants, Enumerations and Structures


//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_SHOW_TRADE_LEVELS property of displaying trade levels on the chart (levels of open

positions, Stop Loss, Take Profit and pending orders).


//+------------------------------------------------------------------+
//| Checks if trading levels are displayed on chart

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

2000-2016, MetaQuotes Software Corp.

290

Standard Constants, Enumerations and Structures


}

CHART_DRAG_TRADE_LEVELS property of enabling the ability to drag trading levels on a chart

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

CHART_SHOW_DATE_SCALE property of displaying the time scale on a chart.

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

2000-2016, MetaQuotes Software Corp.

291

Standard Constants, Enumerations and Structures


//| Checks if the time scale is displayed on chart

//+------------------------------------------------------------------+
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);
}

CHART_SHOW_PRICE_SCALE property of displaying the price scale on a chart.

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

292

Standard Constants, Enumerations and Structures


ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PRICE_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 price scale on chart

//+------------------------------------------------------------------+
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);
}

CHART_SHOW_ONE_CLICK property of displaying the "One click trading" panel on a chart.

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

2000-2016, MetaQuotes Software Corp.

293

Standard Constants, Enumerations and Structures


}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of the "One click trading" panel

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

2000-2016, MetaQuotes Software Corp.

294

Standard Constants, Enumerations and Structures


//| of the chart in percentage values (from 10% up to 50%).

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

//| should be set to false.

//+-----------------------------------------------------------------------------------------+
bool ChartFixedPositionSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value

2000-2016, MetaQuotes Software Corp.

295

Standard Constants, Enumerations and Structures


if(!ChartSetDouble(chart_ID,CHART_FIXED_POSITION,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_FIXED_MAX property of the chart's fixed maximum.

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

//| To change the value of the property, CHART_SCALEFIX property

//| value should be preliminarily set to true.

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

2000-2016, MetaQuotes Software Corp.

296

Standard Constants, Enumerations and Structures


}

CHART_FIXED_MIN property of the chart's fixed minimum.

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

//| To change the value of the property, CHART_SCALEFIX property

//| value should be preliminarily set to true.

//+------------------------------------------------------------------+
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);
}

CHART_POINTS_PER_BAR value of scale in points per bar.

//+------------------------------------------------------------------+
//| Gets the value of chart scale in points per bar

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

2000-2016, MetaQuotes Software Corp.

297

Standard Constants, Enumerations and Structures


double ChartPointsPerBarGet(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_POINTS_PER_BAR,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 scale in points per bar.

//| To view the result of this property's value change, the value of

//| CHART_SCALE_PT_PER_BAR property should be preliminarily set to true. |


//+----------------------------------------------------------------------+
bool ChartPointsPerBarSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_POINTS_PER_BAR,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

CHART_PRICE_MIN returns the value of the chart minimum.

//+----------------------------------------------------------------------+
//| 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))

2000-2016, MetaQuotes Software Corp.

298

Standard Constants, Enumerations and Structures


{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}

CHART_PRICE_MAX returns the value of the chart maximum.

//+----------------------------------------------------------------------+
//| 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);
}

CHART_COMMENT comment on the chart.

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

2000-2016, MetaQuotes Software Corp.

299

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| Gets comment in the upper left corner of chart

//+------------------------------------------------------------------+
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);
}

Panel for chart properties


//--- connect the library of control elements
#include <ChartObjects\ChartObjectsTxtControls.mqh>
//--- predefined constants
#define X_PROPERTY_NAME_1

10

#define X_PROPERTY_VALUE_1

225 // x coordinate of the property value in the first column

// x coordinate of the property name in the first column

#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

285 // x coordinate of the button in the first column

#define X_BUTTON_2

700 // x coordinate of the button in the second column

#define Y_PROPERTY_1

30

#define Y_PROPERTY_2

286 // y coordinate of the beginning of the third column

#define Y_DISTANCE

16

// y coordinate of the beginning of the first and second column


// y axial distance between the lines

#define LAST_PROPERTY_NUMBER 111 // number of the last graphical property


//--- input parameters
input color InpFirstColor=clrDodgerBlue; // Color of odd lines
input color InpSecondColor=clrGoldenrod; // Color of even lines
//--- variables and arrays
CChartObjectLabel

ExtLabelsName[];

CChartObjectLabel

ExtLabelsValue[]; // labels for displaying property values

// labels for displaying property names

CChartObjectButton ExtButtons[];

// buttons

int

ExtNumbers[];

// property indices

string

ExtNames[];

// property names

uchar

ExtDataTypes[];

// property data types (integer, double, string)

uint

ExtGroupTypes[];

// array that stores the data on belonging of properties to on

uchar

ExtDrawTypes[];

// array that stores the data on the type of property display

double

ExtMaxValue[];

// maximum property values that are possible when working with

double

ExtMinValue[];

// minimum property values that are possible when working with

2000-2016, MetaQuotes Software Corp.

300

Standard Constants, Enumerations and Structures


double

ExtStep[];

// steps for changing properties

int

ExtCount;

// total number of all properties

color

ExtColors[2];

// array of colors for displaying lines

string

ExtComments[2];

// array of comments (for CHART_COMMENT property)

//+------------------------------------------------------------------+
//| 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

2000-2016, MetaQuotes Software Corp.

301

Standard Constants, Enumerations and Structures


int index=(int)StringToInteger(obj_name[1]);
//--- unpress the button
ExtButtons[index].State(false);
//--- set the new value of the property depending on its type
if(ExtDataTypes[index]=='I')
ChangeIntegerProperty(index);
if(ExtDataTypes[index]=='D')
ChangeDoubleProperty(index);
if(ExtDataTypes[index]=='S')
ChangeStringProperty(index);
}
}
//--- re-draw property values
RedrawProperties();
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Changes an integer property of chart

//+------------------------------------------------------------------+
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);
}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

302

Standard Constants, Enumerations and Structures


//| Changes a string property of chart

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

case clrGreen: return(clrBlue);


case clrBlue:

return(clrBlack);

default:

return(clrWhite);

}
}
//+------------------------------------------------------------------+
//| Re-draws property values

//+------------------------------------------------------------------+
void RedrawProperties(void)
{
//--- property value text
string text;
long

value;

//--- loop of the number of properties


for(int i=0;i<ExtCount;i++)
{
text="";
switch(ExtDataTypes[i])

2000-2016, MetaQuotes Software Corp.

303

Standard Constants, Enumerations and Structures


{
case 'I':
//--- receive the current property value
if(!ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[i],0,value))
break;
//--- integer property text
switch(ExtDrawTypes[i])
{
//--- color property
case 'C':
text=(string)((color)value);
break;
//--- boolean property
case 'B':
text=(string)((bool)value);
break;
//--- ENUM_CHART_MODE enumeration property
case 'M':
text=EnumToString((ENUM_CHART_MODE)value);
break;
//--- ENUM_CHART_VOLUME_MODE enumeration property
case 'V':
text=EnumToString((ENUM_CHART_VOLUME_MODE)value);
break;
//--- int type number
default:
text=IntegerToString(value);
break;
}
break;
case 'D':
//--- double property text
text=DoubleToString(ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[i]),4);
break;
case 'S':
//--- string property text
text=ChartGetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[i]);
break;
}
//--- display property value
ExtLabelsValue[i].Description(text);
}
}
//+------------------------------------------------------------------+
//| Creates panel for managing chart properties

//+------------------------------------------------------------------+
bool PrepareControls(void)
{
//--- allocate memory for arrays with a reserve

2000-2016, MetaQuotes Software Corp.

304

Standard Constants, Enumerations and Structures


MemoryAllocation(LAST_PROPERTY_NUMBER+1);
//--- variables
int i=0;

// loop variable

int col_1=0; // number of properties in the first column


int col_2=0; // number of properties in the second column
int col_3=0; // number of properties in the third column
//--- current number of properties - 0
ExtCount=0;
//--- looking for properties in the loop
while(i<=LAST_PROPERTY_NUMBER)
{
//--- store the current number of the property
ExtNumbers[ExtCount]=i;
//--- increase the value of the loop variable
i++;
//--- check if there is a property with such a number

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

2000-2016, MetaQuotes Software Corp.

305

Standard Constants, Enumerations and Structures


//--- free the memory not used by arrays
MemoryAllocation(ExtCount);
//--- re-draw property values
RedrawProperties();
ChartRedraw();
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Allocates memory for arrays

//+------------------------------------------------------------------+
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

//| ENUM_CHART_PROPERTIES enumerations

//+------------------------------------------------------------------+
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';

// property from ENUM_CHART_PROPERTY_INTEGER enumeration

GetTypes(ind,group_type,draw_type); // define property display parameters


return(true);
}
//--- check if the property is of double type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_DOUBLE)ind);
if(_LastError==0)
{
data_type='D';

// property from ENUM_CHART_PROPERTY_DOUBLE enumeration

GetTypes(ind,group_type,draw_type); // define property display parameters


return(true);
}

2000-2016, MetaQuotes Software Corp.

306

Standard Constants, Enumerations and Structures


//--- check if the property is of string type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_STRING)ind);
if(_LastError==0)
{
data_type='S';

// property from ENUM_CHART_PROPERTY_STRING enumeration

GetTypes(ind,group_type,draw_type); // define property display parameters


return(true);
}
//--- property does not belong to any enumeration
return(false);
}
//+------------------------------------------------------------------+
//| Defines the group in which property should be stored,

//| as well as its display type

//+------------------------------------------------------------------+
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

//| defines its display type in case of a positive answer

//+----------------------------------------------------------------------+
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:

2000-2016, MetaQuotes Software Corp.

307

Standard Constants, Enumerations and Structures


case CHART_WIDTH_IN_BARS:
case CHART_WIDTH_IN_PIXELS:
draw_type='I';
break;
//--- double properties
case CHART_PRICE_MIN:
case CHART_PRICE_MAX:
draw_type='D';
break;

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

//| defines its display type in case of a positive answer

//+----------------------------------------------------------------------+
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:

2000-2016, MetaQuotes Software Corp.

308

Standard Constants, Enumerations and Structures


case CHART_COLOR_CHART_UP:
case CHART_COLOR_CHART_DOWN:
case CHART_COLOR_CHART_LINE:
case CHART_COLOR_CANDLE_BULL:
case CHART_COLOR_CANDLE_BEAR:
case CHART_COLOR_BID:
case CHART_COLOR_ASK:
case CHART_COLOR_LAST:
case CHART_COLOR_STOP_LEVEL:
draw_type='C';
break;
//--- property does not belong to the second group
default:
return(false);
}
//--- property belongs to the second group
group_type=2;
return(true);
}
//+-----------------------------------------------------------------------+
//| Called only if it is already known that property does not belong

//| to the second and third property groups

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

2000-2016, MetaQuotes Software Corp.

309

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Creates label and button for property

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

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Creates button

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

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

310

Standard Constants, Enumerations and Structures


//| Defines maximum and minimum property value and step

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

311

Standard Constants, Enumerations and Structures


step=30;
break;
//--- default values
default:
max=1;
min=0;
step=1;
}
}

2000-2016, MetaQuotes Software Corp.

312

Standard Constants, Enumerations and Structures

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.

2000-2016, MetaQuotes Software Corp.

313

Standard Constants, Enumerations and Structures

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

Trend Line By Angle

OBJ_CYCLES

Cycle Lines

OBJ_ARROWED_LINE

Arrowed Line

OBJ_CHANNEL

Equidistant Channel

OBJ_STDDEVCHANNEL

Standard Deviation Channel

OBJ_REGRESSION

Linear Regression Channel

OBJ_PITCHFORK

Andrews Pitchfork

OBJ_GANNLINE

Gann Line

OBJ_GANNFAN

Gann Fan

OBJ_GANNGRID

Gann Grid

OBJ_FIBO

Fibonacci Retracement

OBJ_FIBOTIMES

Fibonacci Time Zones

OBJ_FIBOFAN

Fibonacci Fan

OBJ_FIBOARC

Fibonacci Arcs

OBJ_FIBOCHANNEL

Fibonacci Channel

OBJ_EXPANSION

Fibonacci Expansion

OBJ_ELLIOTWAVE5

Elliott Motive Wave

OBJ_ELLIOTWAVE3

Elliott Correction Wave

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

2000-2016, MetaQuotes Software Corp.

314

Standard Constants, Enumerations and Structures


OBJ_ARROW_DOWN

Arrow Down

OBJ_ARROW_STOP

Stop Sign

OBJ_ARROW_CHECK

Check Sign

OBJ_ARROW_LEFT_PRICE

Left Price Label

OBJ_ARROW_RIGHT_PRICE

Right Price Label

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

The "Rectangle label" object


for creating and designing the
custom graphical interface.

2000-2016, MetaQuotes Software Corp.

315

Standard Constants, Enumerations and Structures

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style


input int

InpWidth=3;

// Line width

input bool

InpBack=false;

// Background line

input bool

InpSelection=true;

// Highlight to move

input bool

InpRay=true;

// Line's continuation down

2000-2016, MetaQuotes Software Corp.

316

Standard Constants, Enumerations and Structures


input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style


const int

width=1,

// line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray=true,

// line's continuation down

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

317

Standard Constants, Enumerations and Structures


ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the vertical line

//+------------------------------------------------------------------+
bool VLineMove(const long

chart_ID=0,

// chart's ID

const string name="VLine", // line name


datetime

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

const string name="VLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete the vertical line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{

2000-2016, MetaQuotes Software Corp.

318

Standard Constants, Enumerations and Structures


//--- 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 line 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 points for drawing the line
int d=InpDate*(bars-1)/100;
//--- create a vertical line
if(!VLineCreate(0,InpName,0,date[d],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpRay,InpHidden,InpZOrder))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int h_steps=bars/2;
//--- move the line
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!VLineMove(0,InpName,date[d]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}

2000-2016, MetaQuotes Software Corp.

319

Standard Constants, Enumerations and Structures


//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
VLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

320

Standard Constants, Enumerations and Structures

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style


input int

InpWidth=3;

// Line width

input bool

InpBack=false;

// Background line

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create the horizontal line

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

2000-2016, MetaQuotes Software Corp.

321

Standard Constants, Enumerations and Structures


bool HLineCreate(const long

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

const ENUM_LINE_STYLE style=STYLE_SOLID, // 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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

322

Standard Constants, Enumerations and Structures


const string name="HLine", // line name
double

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

const string name="HLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete a horizontal line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

323

Standard Constants, Enumerations and Structures


//--- array for storing the price values to be used
//--- for setting and changing line anchor point's coordinates
double price[];
//--- memory allocation
ArrayResize(price,accuracy);
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int p=InpPrice*(accuracy-1)/100;
//--- create a horizontal line
if(!HLineCreate(0,InpName,0,price[p],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the line
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!HLineMove(0,InpName,price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
HLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);

2000-2016, MetaQuotes Software Corp.

324

Standard Constants, Enumerations and Structures


//--}

2000-2016, MetaQuotes Software Corp.

325

Standard Constants, Enumerations and Structures

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style

2000-2016, MetaQuotes Software Corp.

326

Standard Constants, Enumerations and Structures


input int

InpWidth=2;

// Line width

input bool

InpBack=false;

// Background line

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Line's continuation to the left

input bool

InpRayRight=false;

// Line's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// line color

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style


const int

width=1,

// line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// line's continuation to the left

const bool

ray_right=false,

// line's continuation to the right

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

327

Standard Constants, Enumerations and Structures


//--- 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 continuation of the line'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 line's display to the right
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 trend line anchor point

//+------------------------------------------------------------------+
bool TrendPointChange(const long

chart_ID=0,

// chart's ID

const string name="TrendLine", // line name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="TrendLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete a trend line

2000-2016, MetaQuotes Software Corp.

328

Standard Constants, Enumerations and Structures


if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default

//| values for empty ones

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

2000-2016, MetaQuotes Software Corp.

329

Standard Constants, Enumerations and Structures


//--- 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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!TrendCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,InpStyle,
InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))

2000-2016, MetaQuotes Software Corp.

330

Standard Constants, Enumerations and Structures


return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- move the second anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- loop counter
int h_steps=bars/2;
//--- move both anchor points horizontally at the same time
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);

2000-2016, MetaQuotes Software Corp.

331

Standard Constants, Enumerations and Structures


//--- delete a trend line
TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

332

Standard Constants, Enumerations and Structures

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;

// Line's slope angle

input color

InpColor=clrRed;

// Line color

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style

2000-2016, MetaQuotes Software Corp.

333

Standard Constants, Enumerations and Structures


input int

InpWidth=2;

// Line width

input bool

InpBack=false;

// Background line

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Line's continuation to the left

input bool

InpRayRight=true;

// Line's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style


const int

width=1,

// line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// line's continuation to the left

const bool

ray_right=true,

// line's continuation to the righ

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- create the second point to facilitate dragging the trend line by mouse
datetime time2=0;
double

price2=0;

//--- set anchor points' coordinates if they are not set


ChangeTrendEmptyPoints(time,price,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line using 2 points
if(!ObjectCreate(chart_ID,name,OBJ_TRENDBYANGLE,sub_window,time,price,time2,price2))
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- change trend line's slope angle; when changing the angle, coordinates of the second
//--- point of the line are redefined automatically according to the angle's new value
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set line 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);

2000-2016, MetaQuotes Software Corp.

334

Standard Constants, Enumerations and Structures


//--- 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 continuation of the line'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 line's display to the right
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);
}
//+------------------------------------------------------------------+
//| Change trend line anchor point's coordinates

//+------------------------------------------------------------------+
bool TrendPointChange(const long

chart_ID=0,

// chart's ID

const string name="TrendLine", // line name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="TrendLine", // trend line name

2000-2016, MetaQuotes Software Corp.

335

Standard Constants, Enumerations and Structures


const double angle=45)

// trend line's slope angle

{
//--- 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

const string name="TrendLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete a trend line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default

//| values for empty ones

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

2000-2016, MetaQuotes Software Corp.

336

Standard Constants, Enumerations and Structures


time2=second_point_time[0];
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create a trend line
if(!TrendByAngleCreate(0,InpName,0,date[d1],price[p1],InpAngle,InpColor,InpStyle,
InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}

2000-2016, MetaQuotes Software Corp.

337

Standard Constants, Enumerations and Structures


//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move and rotate the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point and change the line's slope angle
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,date[d1],price[p1]))
return;
if(!TrendAngleChange(0,InpName,18*(i+1)))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

338

Standard Constants, Enumerations and Structures

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;

// Color of cycle lines

input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Style of cycle lines


input int

InpWidth=1;

// Width of cycle lines

2000-2016, MetaQuotes Software Corp.

339

Standard Constants, Enumerations and Structures


input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// color of cycle lines

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of cycle lines


const int

width=1,

// width of cycle lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

340

Standard Constants, Enumerations and Structures


//--- 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 CyclesPointChange(const long

chart_ID=0,

// chart's ID

const string name="Cycles", // object name


const int

point_index=0, // anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Cycles") // object name


{
//--- reset the error value
ResetLastError();
//--- delete cycle lines
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete cycle lines! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

2000-2016, MetaQuotes Software Corp.

341

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Check the values of cycle lines' anchor points and set default

//| values for empty ones

//+------------------------------------------------------------------+
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);

2000-2016, MetaQuotes Software Corp.

342

Standard Constants, Enumerations and Structures


//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing cycle lines
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!CyclesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,1,date[d2],price[p2]))
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);
}

2000-2016, MetaQuotes Software Corp.

343

Standard Constants, Enumerations and Structures


//--- 1 second of delay
Sleep(1000);
//--- loop counter
h_steps=bars/4;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,0,date[d1],price[p1]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
CyclesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

344

Standard Constants, Enumerations and Structures

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

InpName="ArrowedLine"; // 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

input ENUM_LINE_STYLE InpStyle=STYLE_DASH;

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

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

2000-2016, MetaQuotes Software Corp.

345

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Create an arrowed line by the given coordinates

//+------------------------------------------------------------------+
bool ArrowedLineCreate(const long

chart_ID=0,

// chart's ID

const string

name="ArrowedLine", // line name

const int

sub_window=0,

// subwindow index

datetime

time1=0,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// line color

const ENUM_LINE_STYLE style=STYLE_SOLID,

// 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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

346

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| Move arrowed line's anchor point

//+------------------------------------------------------------------+
bool ArrowedLinePointChange(const long

chart_ID=0,

// chart's ID

const string name="ArrowedLine", // line name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="ArrowedLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete an arrowed line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to create an arrowed line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor points' values and set default values

//| for empty ones

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

2000-2016, MetaQuotes Software Corp.

347

Standard Constants, Enumerations and Structures


void ChangeArrowedLineEmptyPoints(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 line anchor points' coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{

2000-2016, MetaQuotes Software Corp.

348

Standard Constants, Enumerations and Structures


Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an arrowed line
if(!ArrowedLineCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the second anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!ArrowedLinePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;

2000-2016, MetaQuotes Software Corp.

349

Standard Constants, Enumerations and Structures


//--- move the point
if(!ArrowedLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- loop counter
int h_steps=bars/2;
//--- move both anchor points horizontally at the same time
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!ArrowedLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ArrowedLinePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);
//--- delete an arrowed line
ArrowedLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

350

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

351

Standard Constants, Enumerations and Structures


input int

InpPrice3=40;

// 3 rd point's price, %

input color

InpColor=clrRed;

// Channel color

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of channel lines


input int

InpWidth=2;

// Channel line width

input bool

InpBack=false;

// Background channel

input bool

InpFill=false;

// Filling the channel with color

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Channel's continuation to the left

input bool

InpRayRight=false;

// Channel's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// channel color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines


const int

width=1,

// width of channel lines

const bool

fill=false,

// filling the channel with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// channel's continuation to the left

const bool

ray_right=false,

// channel's continuation to the right

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

352

Standard Constants, Enumerations and Structures


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

const string name="Channel", // channel name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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);
}

2000-2016, MetaQuotes Software Corp.

353

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Delete the channel

//+------------------------------------------------------------------+
bool ChannelDelete(const long

chart_ID=0,

// chart's ID

const string name="Channel") // channel name


{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values

//| for empty ones

//+-------------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

354

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| 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
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the equidistant channel

if(!ChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],InpColor,

2000-2016, MetaQuotes Software Corp.

355

Standard Constants, Enumerations and Structures


InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/6;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!ChannelPointChange(0,InpName,1,date[d2],price[p2]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,0,date[d1],price[p1]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter

2000-2016, MetaQuotes Software Corp.

356

Standard Constants, Enumerations and Structures


int v_steps=accuracy/10;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
ChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

357

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

358

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines
input int

InpWidth=2;

// Width of channel lines

input bool

InpFill=false;

// Filling the channel with color

input bool

InpBack=false;

// Background channel

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Channel's continuation to the left

input bool

InpRayRight=false;

// Channel's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

datetime

time2=0,

// second point time

const double

deviation=1.0,

// deviation

const color

clr=clrRed,

// channel color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines


const int

width=1,

// width of channel lines

const bool

fill=false,

// filling the channel with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// channel's continuation to the

const bool

ray_right=false,

// channel's continuation to the

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

359

Standard Constants, Enumerations and Structures


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

const string name="Channel", // channel name


const int

point_index=0,

// anchor point index

datetime

time=0)

// anchor point time coordinate

{
//--- 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

const string name="Channel", // channel name


const double deviation=1.0)

2000-2016, MetaQuotes Software Corp.

// deviation

360

Standard Constants, Enumerations and Structures


{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation))
{
Print(__FUNCTION__,
": failed to change channel deviation! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel

//+------------------------------------------------------------------+
bool StdDevChannelDelete(const long

chart_ID=0,

// chart's ID

const string name="Channel") // channel name


{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values

//| for empty ones

//+-------------------------------------------------------------------------+
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];
}

2000-2016, MetaQuotes Software Corp.

361

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| 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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create standard deviation channel
if(!StdDevChannelCreate(0,InpName,0,date[d1],date[d2],InpDeviation,InpColor,InpStyle,
InpWidth,InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second

2000-2016, MetaQuotes Software Corp.

362

Standard Constants, Enumerations and Structures


ChartRedraw();
Sleep(1000);
//--- now, move the channel horizontally to the right and expand it
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!StdDevChannelPointChange(0,InpName,0,date[d1]))
return;
if(!StdDevChannelPointChange(0,InpName,1,date[d2]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
double v_steps=InpDeviation*2;
//--- expand the channel
for(double i=InpDeviation;i<v_steps;i+=10.0/accuracy)
{
if(!StdDevChannelDeviationChange(0,InpName,i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
StdDevChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---

2000-2016, MetaQuotes Software Corp.

363

Standard Constants, Enumerations and Structures


}

2000-2016, MetaQuotes Software Corp.

364

Standard Constants, Enumerations and Structures

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

InpName="Regression"; // Channel name

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 ENUM_LINE_STYLE InpStyle=STYLE_DASH;

// Style of channel lines

input int

// Width of channel lines

InpWidth=2;

2000-2016, MetaQuotes Software Corp.

365

Standard Constants, Enumerations and Structures


input bool

InpFill=false;

// Filling the channel with color

input bool

InpBack=false;

// Background channel

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Channel's continuation to the left

input bool

InpRayRight=false;

// Channel's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create Linear Regression Channel by the given coordinates

//+------------------------------------------------------------------+
bool RegressionCreate(const long

chart_ID=0,

// chart's ID

const string

name="Regression", // channel name

const int

sub_window=0,

// subwindow index

datetime

time1=0,

// first point time

datetime

time2=0,

// second point time

const color

clr=clrRed,

// channel color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines


const int

width=1,

// width of channel lines

const bool

fill=false,

// filling the channel with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// channel's continuation to the lef

const bool

ray_right=false,

// channel's continuation to the rig

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

366

Standard Constants, Enumerations and Structures


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

const string name="Channel", // channel name


const int

point_index=0,

// anchor point index

datetime

time=0)

// anchor point time coordinate

{
//--- 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

const string name="Channel") // channel name


{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{

2000-2016, MetaQuotes Software Corp.

367

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values

//| for empty ones

//+-------------------------------------------------------------------------+
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);

2000-2016, MetaQuotes Software Corp.

368

Standard Constants, Enumerations and Structures


//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create linear regression channel
if(!RegressionCreate(0,InpName,0,date[d1],date[d2],InpColor,InpStyle,InpWidth,
InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel horizontally to the right
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!RegressionPointChange(0,InpName,0,date[d1]))
return;
if(!RegressionPointChange(0,InpName,1,date[d2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay

2000-2016, MetaQuotes Software Corp.

369

Standard Constants, Enumerations and Structures


Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
RegressionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

370

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

371

Standard Constants, Enumerations and Structures


input color

InpColor=clrRed;

// Pitchfork color

input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Style of pitchfork lines


input int

InpWidth=1;

// Width of pitchfork lines

input bool

InpBack=false;

// Background pitchfork

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Pitchfork's continuation to the left

input bool

InpRayRight=false;

// Pitchfork's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// color of pitchfork lines

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of pitchfork lines


const int

width=1,

// width of pitchfork lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// pitchfork's continuation to the le

const bool

ray_right=false,

// pitchfork's continuation to the ri

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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)

2000-2016, MetaQuotes Software Corp.

372

Standard Constants, Enumerations and Structures


ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the pitchfork 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);

//--- 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,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="Pitchfork") // pitchfork name

{
//--- 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]);

2000-2016, MetaQuotes Software Corp.

373

Standard Constants, Enumerations and Structures


//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Andrews' Pitchfork anchor point

//+------------------------------------------------------------------+
bool PitchforkPointChange(const long

chart_ID=0,

// chart's ID

const string name="Pitchfork", // channel name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Pitchfork") // channel name


{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Andrews' Pitchfork\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);

2000-2016, MetaQuotes Software Corp.

374

Standard Constants, Enumerations and Structures


}
//+----------------------------------------------------------------------+
//| Check the values of Andrews' Pitchfork anchor points and set default |
//| values for empty ones

//+----------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

375

Standard Constants, Enumerations and Structures


int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Andrews' Pitchfork anchor points
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Andrews' Pitchfork
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the pitchfork
if(!PitchforkCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the pitchfork's anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point

2000-2016, MetaQuotes Software Corp.

376

Standard Constants, Enumerations and Structures


if(!PitchforkPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/8;
//--- move the third anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d3<bars-1)
d3+=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

2000-2016, MetaQuotes Software Corp.

377

Standard Constants, Enumerations and Structures


}
//--- 1 second of delay
Sleep(1000);
//--- delete the pitchfork from the chart
PitchforkDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

378

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

379

Standard Constants, Enumerations and Structures


input double

InpScale=1.0;

// Scale

input color

InpColor=clrRed;

// Line color

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style


input int

InpWidth=2;

// Line width

input bool

InpBack=false;

// Background line

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Line's continuation to the left

input bool

InpRayRight=true;

// Line's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

const double

angle=1.0,

// Gann angle

const double

scale=1.0,

// scale

const color

clr=clrRed,

// line color

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style


const int

width=1,

// line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// line's continuation to the left

const bool

ray_right=true,

// line's continuation to the right

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

380

Standard Constants, Enumerations and Structures


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 highlighting the lines 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);
//--- enable (true) or disable (false) the mode of continuation of the line'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 line's display to the right
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 Gann Line anchor point

//+------------------------------------------------------------------+
bool GannLinePointChange(const long

chart_ID=0,

// chart's ID

const string name="GannLine", // line name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

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

2000-2016, MetaQuotes Software Corp.

381

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| Change Gann angle

//+------------------------------------------------------------------+
bool GannLineAngleChange(const long

chart_ID=0,

// chart's ID

const string name="GannLine", // line name


const double angle=1.0)

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

const string name="GannLine", // line name


const double scale=1.0)

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

const string name="GannLine") // line name


{
//--- reset the error value
ResetLastError();
//--- delete Gann line
if(!ObjectDelete(chart_ID,name))

2000-2016, MetaQuotes Software Corp.

382

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to delete \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Line anchor points and set default

//| values for empty ones

//+------------------------------------------------------------------+
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[];

2000-2016, MetaQuotes Software Corp.

383

Standard Constants, Enumerations and Structures


double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Line
if(!GannLineCreate(0,InpName,0,date[d1],price[p1],date[d2],InpAngle,InpScale,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor point and change the angle
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!GannLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

2000-2016, MetaQuotes Software Corp.

384

Standard Constants, Enumerations and Structures


}
//--- half a second of delay
Sleep(500);
//--- define the current value of Gann angle (changed
//--- after moving the first anchor point)
double curr_angle;
if(!ObjectGetDouble(0,InpName,OBJPROP_ANGLE,0,curr_angle))
return;
//--- loop counter
v_steps=accuracy/8;
//--- change Gann angle
for(int i=0;i<v_steps;i++)
{
if(!GannLineAngleChange(0,InpName,curr_angle-0.05*i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the line from the chart
GannLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

385

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

386

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of fan lines
input int

InpWidth=1;

// Width of fan lines

input bool

InpBack=false;

// Background fan

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

const double

scale=1.0,

// scale

const bool

direction=true,

// trend direction

const color

clr=clrRed,

// fan color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of fan lines


const int

width=1,

// width of fan lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

387

Standard Constants, Enumerations and Structures


//--- 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 Gann Fan anchor point

//+------------------------------------------------------------------+
bool GannFanPointChange(const long

chart_ID=0,

// chart's ID

const string name="GannFan", // fan name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="GannFan", // fan name


const double scale=1.0)

// scale

{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))

2000-2016, MetaQuotes Software Corp.

388

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's trend direction

//+------------------------------------------------------------------+
bool GannFanDirectionChange(const long

chart_ID=0,

// chart's ID

const string name="GannFan", // fan name


const bool

direction=true) // trend direction

{
//--- 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

const string name="GannFan") // fan name


{
//--- reset the error value
ResetLastError();
//--- delete Gann Fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
// | Check the values of Gann Fan anchor points and set default

//| values for empty ones

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

2000-2016, MetaQuotes Software Corp.

389

Standard Constants, Enumerations and Structures


void ChangeGannFanEmptyPoints(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 the coordinates of fan's anchor points
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices

2000-2016, MetaQuotes Software Corp.

390

Standard Constants, Enumerations and Structures


//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Fan
if(!GannFanCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor point
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!GannFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change fan's trend direction to descending one
GannFanDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the fan from the chart
GannFanDelete(0,InpName);
ChartRedraw();

2000-2016, MetaQuotes Software Corp.

391

Standard Constants, Enumerations and Structures


//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

392

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

393

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of grid lines
input int

InpWidth=1;

// Width of fan lines

input bool

InpBack=false;

// Background grid

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

const double

scale=1.0,

// scale

const bool

direction=true,

// trend direction

const color

clr=clrRed,

// grid color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of grid lines


const int

width=1,

// width of grid lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

394

Standard Constants, Enumerations and Structures


//--- 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 Gann Grid anchor point

//+------------------------------------------------------------------+
bool GannGridPointChange(const long

chart_ID=0,

// chart's ID

const string name="GannGrid", // grid name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="GannGrid", // grids


const double scale=1.0)

// scale

{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))

2000-2016, MetaQuotes Software Corp.

395

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's trend direction

//+------------------------------------------------------------------+
bool GannGridDirectionChange(const long

chart_ID=0,

// chart's ID

const string name="GannGrid", // grid name


const bool

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

const string name="GannGrid") // grid name


{
//--- reset the error value
ResetLastError();
//--- delete Gann Grid
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Grid anchor points and set default

//| values for empty ones

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

2000-2016, MetaQuotes Software Corp.

396

Standard Constants, Enumerations and Structures


void ChangeGannGridEmptyPoints(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 grid anchor points' coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices

2000-2016, MetaQuotes Software Corp.

397

Standard Constants, Enumerations and Structures


//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Grid
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Grid
if(!GannGridCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the grid's anchor points
//--- loop counter
int v_steps=accuracy/4;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
if(!GannGridPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point horizontally
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
if(!GannGridPointChange(0,InpName,1,date[d2],0))
return;

2000-2016, MetaQuotes Software Corp.

398

Standard Constants, Enumerations and Structures


//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- change grid's trend direction to descending one
GannGridDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the grid from the chart
GannGridDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

399

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

400

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int

InpWidth=2;

// Line width

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Object's continuation to the left

input bool

InpRayRight=false;

// Object's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create Fibonacci Retracement by the given coordinates

//+------------------------------------------------------------------+
bool FiboLevelsCreate(const long

chart_ID=0,

// chart's ID

const string

name="FiboLevels", // object name

const int

sub_window=0,

// subwindow index

datetime

time1=0,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// object color

const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style


const int

width=1,

// object line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// object's continuation to the left

const bool

ray_right=false,

// object's continuation to the righ

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

401

Standard Constants, Enumerations and Structures


//--- 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 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,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboLevels") // object name

{
//--- 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));
}

2000-2016, MetaQuotes Software Corp.

402

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Retracement anchor point

//+------------------------------------------------------------------+
bool FiboLevelsPointChange(const long

chart_ID=0,

// chart's ID

const string name="FiboLevels", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboLevels") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Retracement\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Retracement anchor points and set

2000-2016, MetaQuotes Software Corp.

403

Standard Constants, Enumerations and Structures


//| default values for empty ones

//+------------------------------------------------------------------+
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();

2000-2016, MetaQuotes Software Corp.

404

Standard Constants, Enumerations and Structures


if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Retracement
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboLevelsCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy*2/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;

2000-2016, MetaQuotes Software Corp.

405

Standard Constants, Enumerations and Structures


//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboLevelsDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

406

Standard Constants, Enumerations and Structures

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style


input int

InpWidth=2;

// Line width

2000-2016, MetaQuotes Software Corp.

407

Standard Constants, Enumerations and Structures


input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// object color

const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style


const int

width=1,

// object line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

408

Standard Constants, Enumerations and Structures


//--- 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 FiboTimesLevelsSet(int

levels,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboTimes") // object name

{
//--- 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

const string name="FiboTimes", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

2000-2016, MetaQuotes Software Corp.

409

Standard Constants, Enumerations and Structures


double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboTimes") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Time Zones\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Time Zones and

//| set default values for empty ones

//+------------------------------------------------------------------+
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)

2000-2016, MetaQuotes Software Corp.

410

Standard Constants, Enumerations and Structures


price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 2 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 3 bars
datetime temp[3];
CopyTime(Symbol(),Period(),time1,3,temp);
//--- set the first point 2 bars left from the second 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 Fibonacci Time Zones anchor points
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array

2000-2016, MetaQuotes Software Corp.

411

Standard Constants, Enumerations and Structures


double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Time Zones
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboTimesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars*2/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,1,date[d2],price[p2]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
h_steps=bars*3/5;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,0,date[d1],price[p1]))

2000-2016, MetaQuotes Software Corp.

412

Standard Constants, Enumerations and Structures


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);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboTimesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

413

Standard Constants, Enumerations and Structures

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;

// Fan line color

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style


input int

InpWidth=2;

// Line width

2000-2016, MetaQuotes Software Corp.

414

Standard Constants, Enumerations and Structures


input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// fan line color

const ENUM_LINE_STYLE style=STYLE_SOLID, // fan line style


const int

width=1,

// fan line width

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

415

Standard Constants, Enumerations and Structures


//--- 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 FiboFanLevelsSet(int

levels,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboFan") // fan name

{
//--- 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

const string name="FiboFan", // fan name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

2000-2016, MetaQuotes Software Corp.

416

Standard Constants, Enumerations and Structures


double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboFan") // fan name


{
//--- reset the error value
ResetLastError();
//--- delete the fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Fan anchor points and set

//| default values for empty ones

//+------------------------------------------------------------------+
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)

2000-2016, MetaQuotes Software Corp.

417

Standard Constants, Enumerations and Structures


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 Fan anchor points
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array

2000-2016, MetaQuotes Software Corp.

418

Standard Constants, Enumerations and Structures


double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboFanCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor points
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled

2000-2016, MetaQuotes Software Corp.

419

Standard Constants, Enumerations and Structures


if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboFanDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

420

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

421

Standard Constants, Enumerations and Structures


input bool

InpFullEllipse=true;

// Shape of the arcs

input color

InpColor=clrRed;

// Line color

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style


input int

InpWidth=2;

// Line width

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const double

scale=1.0,

// scale

const bool

full_ellipse=false, // shape of the arcs

const color

clr=clrRed,

// line color

const ENUM_LINE_STYLE style=STYLE_SOLID,

// 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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

422

Standard Constants, Enumerations and Structures


//--- 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 arcs 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);
//--- 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 FiboArcLevelsSet(int

levels,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboArc") // object name

{
//--- 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));
}

2000-2016, MetaQuotes Software Corp.

423

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Arcs anchor point

//+------------------------------------------------------------------+
bool FiboArcPointChange(const long

chart_ID=0,

// chart's ID

const string name="FiboArc", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboArc") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Arcs anchor points and set default |

2000-2016, MetaQuotes Software Corp.

424

Standard Constants, Enumerations and Structures


//| values for empty ones

//+------------------------------------------------------------------+
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();

2000-2016, MetaQuotes Software Corp.

425

Standard Constants, Enumerations and Structures


if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Arcs
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboArcCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpScale,
InpFullEllipse,InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/5;

2000-2016, MetaQuotes Software Corp.

426

Standard Constants, Enumerations and Structures


//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,1,date[d2],price[p2]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboArcDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

427

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

428

Standard Constants, Enumerations and Structures


input int

InpPrice3=25;

// 3 rd point's price, %

input color

InpColor=clrRed;

// Channel color

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines


input int

InpWidth=2;

// Width of channel lines

input bool

InpBack=false;

// Background channel

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Channel's continuation to the left

input bool

InpRayRight=false;

// Channel's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create Fibonacci Channel by the given coordinates

//+------------------------------------------------------------------+
bool FiboChannelCreate(const long

chart_ID=0,

// chart's ID

const string

name="FiboChannel", // channel name

const int

sub_window=0,

// subwindow index

datetime

time1=0,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// channel color

const ENUM_LINE_STYLE style=STYLE_SOLID,

// style of channel lines

const int

width=1,

// width of channel lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

ray_left=false,

// channel's continuation to the l

const bool

ray_right=false,

// channel's continuation to the r

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

429

Standard Constants, Enumerations and Structures


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

//--- 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,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboChannel") // object name

{
//--- 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

2000-2016, MetaQuotes Software Corp.

430

Standard Constants, Enumerations and Structures


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 Channel anchor point

//+------------------------------------------------------------------+
bool FiboChannelPointChange(const long

chart_ID=0,

// chart's ID

const string name="FiboChannel", // channel name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboChannel") // channel name


{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Channel\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution

2000-2016, MetaQuotes Software Corp.

431

Standard Constants, Enumerations and Structures


return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Channel anchor points and set

//| default values for empty ones

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

2000-2016, MetaQuotes Software Corp.

432

Standard Constants, Enumerations and Structures


//--- 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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Channel
if(!FiboChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/10;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;

2000-2016, MetaQuotes Software Corp.

433

Standard Constants, Enumerations and Structures


//--- move the point
if(!FiboChannelPointChange(0,InpName,0,date[d1],price[p1]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/15;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}

2000-2016, MetaQuotes Software Corp.

434

Standard Constants, Enumerations and Structures


//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
FiboChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

435

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

436

Standard Constants, Enumerations and Structures


input int

InpPrice3=75;

// 3 rd point's price, %

input color

InpColor=clrRed;

// Object color

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of lines


input int

InpWidth=2;

// Width of the lines

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpRayLeft=false;

// Object's continuation to the left

input bool

InpRayRight=false;

// Object's continuation to the right

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create Fibonacci Extension by the given coordinates

//+------------------------------------------------------------------+
bool FiboExpansionCreate(const long

chart_ID=0,

// chart's ID

const string

name="FiboExpansion", // channel name

const int

sub_window=0,

// subwindow index

datetime

time1=0,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// object color

const ENUM_LINE_STYLE style=STYLE_SOLID,

// style of the lines

const int

width=1,

// width of the lines

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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

437

Standard Constants, Enumerations and Structures


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

//--- 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,

// number of level lines

double

&values[],

// values of level lines

color

&colors[],

// color of level lines

ENUM_LINE_STYLE &styles[],

// style of level lines

int

&widths[],

// width of level lines

const long

chart_ID=0,

// chart's ID

const string

name="FiboExpansion") // object name

{
//--- 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

2000-2016, MetaQuotes Software Corp.

438

Standard Constants, Enumerations and Structures


ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,"FE "+DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Expansion anchor point

//+------------------------------------------------------------------+
bool FiboExpansionPointChange(const long

chart_ID=0,

// chart's ID

const string name="FiboExpansion", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="FiboExpansion") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Expansion\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution

2000-2016, MetaQuotes Software Corp.

439

Standard Constants, Enumerations and Structures


return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Expansion anchor points and set

//| default values for empty ones

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

440

Standard Constants, Enumerations and Structures


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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Expansion
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Expansion
if(!FiboExpansionCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)

2000-2016, MetaQuotes Software Corp.

441

Standard Constants, Enumerations and Structures


p1-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/2;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay

2000-2016, MetaQuotes Software Corp.

442

Standard Constants, Enumerations and Structures


Sleep(1000);
//--- delete the object from the chart
FiboExpansionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

443

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

444

Standard Constants, Enumerations and Structures


input int

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, %

input ENUM_ELLIOT_WAVE_DEGREE InpDegree=ELLIOTT_MINOR; // Level


input bool

InpDrawLines=true;

// Displaying the lines

input color

InpColor=clrRed;

// Color of the lines

input ENUM_LINE_STYLE

InpStyle=STYLE_DASH;

// Style of the lines

input int

InpWidth=2;

// Width of the lines

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

datetime

time4=0,

// fourth point time

double

price4=0,

// fourth point price

datetime

time5=0,

// fifth point time

double

price5=0,

// fifth point price

const string

const ENUM_ELLIOT_WAVE_DEGREE degree=ELLIOTT_MINUETTE, // degree


const bool

draw_lines=true,

// displaying the lin

const color

clr=clrRed,

// object color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// style of the lines

const int

width=1,

// width of the lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the obje

const long

z_order=0)

// priority for mouse

{
//--- 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__,

2000-2016, MetaQuotes Software Corp.

445

Standard Constants, Enumerations and Structures


": failed to create \"Elliott Motive 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);
//--- 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)
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);
//--- 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 anchor point of Elliott Motive Wave

//+------------------------------------------------------------------+
bool ElliotWave5PointChange(const long

chart_ID=0,

// chart's ID

const string name="ElliotWave5", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

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

2000-2016, MetaQuotes Software Corp.

446

Standard Constants, Enumerations and Structures


return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Elliott Motive Wave

//+------------------------------------------------------------------+
bool ElliotWave5Delete(const long

chart_ID=0,

// chart's ID

const string name="ElliotWave5") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Elliott Motive Wave\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Elliott Motive Wave's anchor points and

//| set default values for empty ones

//+------------------------------------------------------------------+
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];

2000-2016, MetaQuotes Software Corp.

447

Standard Constants, Enumerations and Structures


//--- 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 5 bars left from the last bar
if(!time3)
time3=temp[4];
//--- if the third point's price is not set, move it 250 points lower than the first one
if(!price3)
price3=price1-250*point;
//--- if the fourth point's time is not set, it will be 3 bars left from the last bar
if(!time4)
time4=temp[6];
//--- if the fourth point's price is not set, move it 550 points lower than the first one
if(!price4)
price4=price1-550*point;
//--- if the fifth point's time is not set, it will be on the last bar
if(!time5)
time5=temp[9];
//--- if the fifth point's price is not set, move it 450 points lower than the first one
if(!price5)
price5=price1-450*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 ||
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates

2000-2016, MetaQuotes Software Corp.

448

Standard Constants, Enumerations and Structures


ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Elliott Motive Wave
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int d4=InpDate4*(bars-1)/100;
int d5=InpDate5*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
int p4=InpPrice4*(accuracy-1)/100;
int p5=InpPrice5*(accuracy-1)/100;
//--- Create Elliott Motive Wave
if(!ElliotWave5Create(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
date[d4],price[p4],date[d5],price[p5],InpDegree,InpDrawLines,InpColor,InpStyle,InpWidth,
InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the fifth anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p5<accuracy-1)
p5+=1;
//--- move the point
if(!ElliotWave5PointChange(0,InpName,4,date[d5],price[p5]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

2000-2016, MetaQuotes Software Corp.

449

Standard Constants, Enumerations and Structures


return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/5;
//--- move the second and third anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p2<accuracy-1)
p2+=1;
if(p3>1)
p3-=1;
//--- shift the points
if(!ElliotWave5PointChange(0,InpName,1,date[d2],price[p2]))
return;
if(!ElliotWave5PointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the first and fourth anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1>1)
p1-=1;
if(p4<accuracy-1)
p4+=1;
//--- shift the points
if(!ElliotWave5PointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ElliotWave5PointChange(0,InpName,3,date[d4],price[p4]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

2000-2016, MetaQuotes Software Corp.

450

Standard Constants, Enumerations and Structures


}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
ElliotWave5Delete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

451

Standard Constants, Enumerations and Structures

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, %

2000-2016, MetaQuotes Software Corp.

452

Standard Constants, Enumerations and Structures


input int

InpPrice3=40;

// 3 rd point's price, %

input ENUM_ELLIOT_WAVE_DEGREE InpDegree=ELLIOTT_MINOR; // Level


input bool

InpDrawLines=true;

// Displaying the lines

input color

InpColor=clrRed;

// Color of the lines

input ENUM_LINE_STYLE

InpStyle=STYLE_DASH;

// Style of the lines

input int

InpWidth=2;

// Width of the lines

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const ENUM_ELLIOT_WAVE_DEGREE degree=ELLIOTT_MINUETTE, // degree


const bool

draw_lines=true,

// displaying the lin

const color

clr=clrRed,

// object color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// style of the lines

const int

width=1,

// width of the lines

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the obje

const long

z_order=0)

// priority for mouse

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

2000-2016, MetaQuotes Software Corp.

453

Standard Constants, Enumerations and Structures


//--- 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)
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);
//--- 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 anchor point of Elliott Correction Wave

//+------------------------------------------------------------------+
bool ElliotWave3PointChange(const long

chart_ID=0,

// chart's ID

const string name="ElliotWave3", // object name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

2000-2016, MetaQuotes Software Corp.

454

Standard Constants, Enumerations and Structures


const string name="ElliotWave3") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Elliott Correction Wave\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Elliott Correction Wave's anchor points

//| and set default values for empty ones

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

2000-2016, MetaQuotes Software Corp.

455

Standard Constants, Enumerations and Structures


//| 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
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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Elliott Correction Wave
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- Create Elliott Correction Wave
if(!ElliotWave3Create(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpDegree,InpDrawLines,InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{

2000-2016, MetaQuotes Software Corp.

456

Standard Constants, Enumerations and Structures


return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!ElliotWave3PointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the first and second anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1>1)
p1-=1;
if(p2<accuracy-1)
p2+=1;
//--- shift the points
if(!ElliotWave3PointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ElliotWave3PointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart

2000-2016, MetaQuotes Software Corp.

457

Standard Constants, Enumerations and Structures


ElliotWave3Delete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

458

Standard Constants, Enumerations and Structures

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

InpName="Rectangle"; // Rectangle name

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of rectangle lines


input int

InpWidth=2;

// Width of rectangle lines

2000-2016, MetaQuotes Software Corp.

459

Standard Constants, Enumerations and Structures


input bool

InpFill=true;

// Filling the rectangle with color

input bool

InpBack=false;

// Background rectangle

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

const color

clr=clrRed,

// rectangle color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of rectangle lines


const int

width=1,

// width of rectangle lines

const bool

fill=false,

// filling rectangle with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

460

Standard Constants, Enumerations and Structures


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 rectangle anchor point

//+------------------------------------------------------------------+
bool RectanglePointChange(const long

chart_ID=0,

// chart's ID

const string name="Rectangle", // rectangle name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Rectangle") // rectangle name


{
//--- reset the error value
ResetLastError();
//--- delete rectangle
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete rectangle! Error code = ",GetLastError());
return(false);

2000-2016, MetaQuotes Software Corp.

461

Standard Constants, Enumerations and Structures


}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of rectangle's anchor points and set default

//| values for empty ones

//+------------------------------------------------------------------+
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[];

2000-2016, MetaQuotes Software Corp.

462

Standard Constants, Enumerations and Structures


double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the rectangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a rectangle
if(!RectangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the rectangle's anchor points
//--- loop counter
int h_steps=bars/2;
//--- move the anchor points
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;

2000-2016, MetaQuotes Software Corp.

463

Standard Constants, Enumerations and Structures


//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the rectangle from the chart
RectangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

464

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

465

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of triangle lines
input int

InpWidth=2;

// Width of triangle lines

input bool

InpFill=false;

// Filling triangle with color

input bool

InpBack=false;

// Background triangle

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// triangle color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of triangle lines


const int

width=1,

// width of triangle lines

const bool

fill=false,

// filling triangle with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

466

Standard Constants, Enumerations and Structures


//--- enable (true) or disable (false) the mode of highlighting the triangle 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);
//--- 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 triangle anchor point

//+------------------------------------------------------------------+
bool TrianglePointChange(const long

chart_ID=0,

// chart's ID

const string name="Triangle", // triangle name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Triangle") // triangle name


{
//--- reset the error value
ResetLastError();
//--- delete the triangle
if(!ObjectDelete(chart_ID,name))

2000-2016, MetaQuotes Software Corp.

467

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to delete the ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of triangle's anchor points and set default

//| values for empty ones

//+------------------------------------------------------------------+
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 ||

2000-2016, MetaQuotes Software Corp.

468

Standard Constants, Enumerations and Structures


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 triangle anchor points' coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the triangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create a triangle
if(!TriangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the triangle anchor points
//--- loop counter

2000-2016, MetaQuotes Software Corp.

469

Standard Constants, Enumerations and Structures


int v_steps=accuracy*3/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars*9/20-1;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2>1)
d2-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,1,date[d2],price[p2]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/4;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!TrianglePointChange(0,InpName,2,date[d3],price[p3]))

2000-2016, MetaQuotes Software Corp.

470

Standard Constants, Enumerations and Structures


return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete triangle from the chart
TriangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

471

Standard Constants, Enumerations and Structures

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

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of ellipse lines

2000-2016, MetaQuotes Software Corp.

472

Standard Constants, Enumerations and Structures


input int

InpWidth=2;

// Width of ellipse lines

input bool

InpFill=false;

// Filling ellipse with color

input bool

InpBack=false;

// Background ellipse

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// first point time

double

price1=0,

// first point price

datetime

time2=0,

// second point time

double

price2=0,

// second point price

datetime

time3=0,

// third point time

double

price3=0,

// third point price

const color

clr=clrRed,

// ellipse color

const ENUM_LINE_STYLE style=STYLE_SOLID, // style of ellipse lines


const int

width=1,

// width of ellipse lines

const bool

fill=false,

// filling ellipse with color

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

473

Standard Constants, Enumerations and Structures


//--- 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 ellipse anchor point

//+------------------------------------------------------------------+
bool EllipsePointChange(const long

chart_ID=0,

// chart's ID

const string name="Ellipse", // ellipse name


const int

point_index=0,

// anchor point index

datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Ellipse") // ellipse name


{
//--- reset the error value
ResetLastError();
//--- delete an ellipse
if(!ObjectDelete(chart_ID,name))
{

2000-2016, MetaQuotes Software Corp.

474

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to delete an ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of ellipse anchor points and set default values |
//| for empty ones

//+------------------------------------------------------------------+
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)

2000-2016, MetaQuotes Software Corp.

475

Standard Constants, Enumerations and Structures


{
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 ellipse anchor points' coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the ellipse
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create an ellipse
if(!EllipseCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the ellipse anchor points
//--- loop counter
int v_steps=accuracy/5;

2000-2016, MetaQuotes Software Corp.

476

Standard Constants, Enumerations and Structures


//--- move the first and second anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!EllipsePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!EllipsePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/5;
//--- move the third anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d3>1)
d3-=1;
//--- move the point
if(!EllipsePointChange(0,InpName,2,date[d3],price[p3]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- delete ellipse from the chart
EllipseDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

477

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=25;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type


input color

InpColor=clrRed;

// Sign color

2000-2016, MetaQuotes Software Corp.

478

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

479

Standard Constants, Enumerations and Structures


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 ArrowThumbUpMove(const long

chart_ID=0,

// chart's ID

const string name="ThumbUp", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

2000-2016, MetaQuotes Software Corp.

480

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Up sign

//+------------------------------------------------------------------+
bool ArrowThumbUpDelete(const long

chart_ID=0,

// chart's ID

const string name="ThumbUp") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

481

Standard Constants, Enumerations and Structures


//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Up sign on the chart
if(!ArrowThumbUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d>1)
d-=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

2000-2016, MetaQuotes Software Corp.

482

Standard Constants, Enumerations and Structures


//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

483

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=75;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type

2000-2016, MetaQuotes Software Corp.

484

Standard Constants, Enumerations and Structures


input color

InpColor=clrRed;

// Sign color

input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const string

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object lis

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

485

Standard Constants, Enumerations and Structures


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 ArrowThumbDownMove(const long

chart_ID=0,

// chart's ID

const string name="ThumbDown", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);

2000-2016, MetaQuotes Software Corp.

486

Standard Constants, Enumerations and Structures


}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Down sign

//+------------------------------------------------------------------+
bool ArrowThumbDownDelete(const long

chart_ID=0,

// chart's ID

const string name="ThumbDown") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

487

Standard Constants, Enumerations and Structures


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[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Down sign on the chart
if(!ArrowThumbDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

2000-2016, MetaQuotes Software Corp.

488

Standard Constants, Enumerations and Structures


return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

489

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=25;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type


input color

InpColor=clrRed;

// Sign color

2000-2016, MetaQuotes Software Corp.

490

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

491

Standard Constants, Enumerations and Structures


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 ArrowUpMove(const long

chart_ID=0,

// chart's ID

const string name="ArrowUp", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

2000-2016, MetaQuotes Software Corp.

492

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Arrow Up sign

//+------------------------------------------------------------------+
bool ArrowUpDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowUp") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

493

Standard Constants, Enumerations and Structures


//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Up sign on the chart
if(!ArrowUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

2000-2016, MetaQuotes Software Corp.

494

Standard Constants, Enumerations and Structures


//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

495

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=75;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type


input color

InpColor=clrRed;

// Sign color

input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

2000-2016, MetaQuotes Software Corp.

496

Standard Constants, Enumerations and Structures


input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const string

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

497

Standard Constants, Enumerations and Structures


//--- 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 ArrowDownMove(const long

chart_ID=0,

// chart's ID

const string name="ArrowDown", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution

2000-2016, MetaQuotes Software Corp.

498

Standard Constants, Enumerations and Structures


return(true);
}
//+------------------------------------------------------------------+
//| Delete Arrow Down sign

//+------------------------------------------------------------------+
bool ArrowDownDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowDown") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

499

Standard Constants, Enumerations and Structures


//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Down sign on the chart
if(!ArrowDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart

2000-2016, MetaQuotes Software Corp.

500

Standard Constants, Enumerations and Structures


ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

501

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=50;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type


input color

InpColor=clrRed;

// Sign color

2000-2016, MetaQuotes Software Corp.

502

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

503

Standard Constants, Enumerations and Structures


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 ArrowStopMove(const long

chart_ID=0,

// chart's ID

const string name="ArrowStop", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor point position


{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

2000-2016, MetaQuotes Software Corp.

504

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Stop sign

//+------------------------------------------------------------------+
bool ArrowStopDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowStop") // label name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

505

Standard Constants, Enumerations and Structures


//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Stop sign on the chart
if(!ArrowStopCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

2000-2016, MetaQuotes Software Corp.

506

Standard Constants, Enumerations and Structures


//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowStopAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowStopDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

507

Standard Constants, Enumerations and Structures

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

InpName="ArrowCheck"; // Sign name

input int

InpDate=10;

// Anchor point date in %

input int

InpPrice=50;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type


input color

InpColor=clrRed;

// Sign color

2000-2016, MetaQuotes Software Corp.

508

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE

InpStyle=STYLE_DOT;

// Border line style

input int

InpWidth=5;

// Sign size

input bool

InpBack=false;

// Background sign

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type


const color

clr=clrRed,

// sign color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// sign size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

509

Standard Constants, Enumerations and Structures


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 ArrowCheckMove(const long

chart_ID=0,

// chart's ID

const string name="ArrowCheck", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

name="ArrowCheck", // object name

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

2000-2016, MetaQuotes Software Corp.

510

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Check sign

//+------------------------------------------------------------------+
bool ArrowCheckDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowCheck") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

511

Standard Constants, Enumerations and Structures


//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Check sign on the chart
if(!ArrowCheckCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

2000-2016, MetaQuotes Software Corp.

512

Standard Constants, Enumerations and Structures


//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowCheckAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowCheckDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

513

Standard Constants, Enumerations and Structures

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

// Price label name

input int

InpDate=100;

// Anchor point date in %

input int

InpPrice=10;

// Anchor point price in %

input color

InpColor=clrRed;

// Price label color

input ENUM_LINE_STYLE

InpStyle=STYLE_SOLID; // Border line style

input int

InpWidth=2;

// Price label size

input bool

InpBack=false;

// Background label

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create the left price label

2000-2016, MetaQuotes Software Corp.

514

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
bool ArrowLeftPriceCreate(const long

chart_ID=0,

// chart's ID

const string

name="LeftPrice",

// price label name

const int

sub_window=0,

// subwindow index

datetime

time=0,

// anchor point time

double

price=0,

// anchor point price

const color

clr=clrRed,

// price label color

const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style


const int

width=1,

// price label size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

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

2000-2016, MetaQuotes Software Corp.

515

Standard Constants, Enumerations and Structures


bool ArrowLeftPriceMove(const long

chart_ID=0,

// chart's ID

const string name="LeftPrice", // label name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="LeftPrice") // label name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the left price label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

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

2000-2016, MetaQuotes Software Corp.

516

Standard Constants, Enumerations and Structures


//--- 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
//--- for setting and changing label anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the left price label on the chart
if(!ArrowLeftPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;

2000-2016, MetaQuotes Software Corp.

517

Standard Constants, Enumerations and Structures


}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowLeftPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowLeftPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

518

Standard Constants, Enumerations and Structures

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

InpName="RightPrice"; // Price label name

input int

InpDate=0;

// Anchor point date in %

input int

InpPrice=90;

// Anchor point price in %

input color

InpColor=clrRed;

// Price label color

input ENUM_LINE_STYLE

InpStyle=STYLE_SOLID; // Border line style

input int

InpWidth=2;

// Price label size

input bool

InpBack=false;

// Background label

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| Create the right price label

2000-2016, MetaQuotes Software Corp.

519

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
bool ArrowRightPriceCreate(const long

chart_ID=0,

// chart's ID

const string

name="RightPrice", // price label name

const int

sub_window=0,

// subwindow index

datetime

time=0,

// anchor point time

double

price=0,

// anchor point price

const color

clr=clrRed,

// price label color

const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style


const int

width=1,

// price label size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

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

2000-2016, MetaQuotes Software Corp.

520

Standard Constants, Enumerations and Structures


bool ArrowRightPriceMove(const long

chart_ID=0,

// chart's ID

const string name="RightPrice", // label name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="RightPrice") // label name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the right price label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

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

2000-2016, MetaQuotes Software Corp.

521

Standard Constants, Enumerations and Structures


//--- 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
//--- for setting and changing label anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the right price label on the chart
if(!ArrowRightPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;

2000-2016, MetaQuotes Software Corp.

522

Standard Constants, Enumerations and Structures


}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowRightPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowRightPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

523

Standard Constants, Enumerations and Structures

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,

// anchor point time

double

price=0,

// anchor point price

const color

clr=C'3,95,172',

// sign color

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when highlighted)


const int

width=1,

// line size (when highlighted)

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

2000-2016, MetaQuotes Software Corp.

524

Standard Constants, Enumerations and Structures


const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

const string name="ArrowBuy", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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))

2000-2016, MetaQuotes Software Corp.

525

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Buy sign

//+------------------------------------------------------------------+
bool ArrowBuyDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowBuy") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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[];

// array for storing Low prices of visible bars

double

high[]; // array for storing High prices of visible bars

//--- number of visible bars in the chart window


int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

2000-2016, MetaQuotes Software Corp.

526

Standard Constants, Enumerations and Structures


//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,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;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- create Buy signs in Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyCreate(0,"ArrowBuy_"+(string)i,0,date[i],low[i],InpColor))
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);
}
//--- move Buy signs to High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyMove(0,"ArrowBuy_"+(string)i,date[i],high[i]))
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);
}

2000-2016, MetaQuotes Software Corp.

527

Standard Constants, Enumerations and Structures


//--- delete Buy signs
for(int i=0;i<bars;i++)
{
if(!ArrowBuyDelete(0,"ArrowBuy_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--}

2000-2016, MetaQuotes Software Corp.

528

Standard Constants, Enumerations and Structures

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,

// anchor point time

double

price=0,

// anchor point price

const color

clr=C'225,68,29',

// sign color

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when highlighted)


const int

width=1,

// line size (when highlighted)

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

2000-2016, MetaQuotes Software Corp.

529

Standard Constants, Enumerations and Structures


const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

const string name="ArrowSell", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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))

2000-2016, MetaQuotes Software Corp.

530

Standard Constants, Enumerations and Structures


{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Sell sign

//+------------------------------------------------------------------+
bool ArrowSellDelete(const long

chart_ID=0,

// chart's ID

const string name="ArrowSell") // sign name


{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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[];

// array for storing Low prices of visible bars

double

high[]; // array for storing High prices of visible bars

//--- number of visible bars in the chart window


int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

2000-2016, MetaQuotes Software Corp.

531

Standard Constants, Enumerations and Structures


//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,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;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- create Sell signs in High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellCreate(0,"ArrowSell_"+(string)i,0,date[i],high[i],InpColor))
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);
}
//--- move Sell signs to Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellMove(0,"ArrowSell_"+(string)i,date[i],low[i]))
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);
}

2000-2016, MetaQuotes Software Corp.

532

Standard Constants, Enumerations and Structures


//--- delete Sell signs
for(int i=0;i<bars;i++)
{
if(!ArrowSellDelete(0,"ArrowSell_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--}

2000-2016, MetaQuotes Software Corp.

533

Standard Constants, Enumerations and Structures

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;

// Anchor point date in %

input int

InpPrice=50;

// Anchor point price in %

input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP;

// Anchor type

2000-2016, MetaQuotes Software Corp.

534

Standard Constants, Enumerations and Structures


input color

InpColor=clrDodgerBlue; // Arrow color

input ENUM_LINE_STYLE

InpStyle=STYLE_SOLID;

// Border line style

input int

InpWidth=10;

// Arrow size

input bool

InpBack=false;

// Background arrow

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const uchar

arrow_code=252,

// arrow code

const string

const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor point position


const color

clr=clrRed,

// arrow color

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// border line style

const int

width=3,

// arrow size

const bool

back=false,

// in the background

const bool

selection=true,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

535

Standard Constants, Enumerations and Structures


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

//+------------------------------------------------------------------+
bool ArrowMove(const long

chart_ID=0,

// chart's ID

const string name="Arrow", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Arrow", // object name


const uchar

code=252)

// arrow code

{
//--- reset the error value
ResetLastError();
//--- change the arrow code
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,code))
{

2000-2016, MetaQuotes Software Corp.

536

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to change the arrow code! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change anchor type

//+------------------------------------------------------------------+
bool ArrowAnchorChange(const long
const string

chart_ID=0,

// chart's ID

name="Arrow",

// object name

const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type


{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete an arrow

//+------------------------------------------------------------------+
bool ArrowDelete(const long

chart_ID=0,

// chart's ID

const string name="Arrow") // arrow name


{
//--- reset the error value
ResetLastError();
//--- delete an arrow
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete an arrow! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)

2000-2016, MetaQuotes Software Corp.

537

Standard Constants, Enumerations and Structures


{
//--- 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
//--- for setting and changing sign anchor point coordinates
datetime date[];
double

price[];

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the arrow
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create an arrow on the chart

2000-2016, MetaQuotes Software Corp.

538

Standard Constants, Enumerations and Structures


if(!ArrowCreate(0,InpName,0,date[d],price[p],32,InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- consider all cases of creating arrows in the loop
for(int i=33;i<256;i++)
{
if(!ArrowCodeChange(0,InpName,(uchar)i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// half a second of delay
Sleep(500);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the arrow from the chart
ArrowDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

539

Standard Constants, Enumerations and Structures

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;

// Slope angle in degrees

input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_BOTTOM; // Anchor type


input bool

InpBack=false;

// Background object

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

2000-2016, MetaQuotes Software Corp.

540

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Creating Text object

//+------------------------------------------------------------------+
bool TextCreate(const long

chart_ID=0,

// chart's ID

name="Text",

// object name

const int

sub_window=0,

// subwindow index

datetime

time=0,

// anchor point time

double

price=0,

// anchor point price

const string

text="Text",

// the text itself

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

const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type


const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

541

Standard Constants, Enumerations and Structures


//--- 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 TextMove(const long

chart_ID=0,

// chart's ID

const string name="Text", // object name


datetime

time=0,

// anchor point time coordinate

double

price=0)

// anchor point price coordinate

{
//--- 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

const string name="Text", // object name


const string text="Text") // 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);
}

2000-2016, MetaQuotes Software Corp.

542

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
//| Delete Text object

//+------------------------------------------------------------------+
bool TextDelete(const long

chart_ID=0,

// chart's ID

const string name="Text") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

//+------------------------------------------------------------------+
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

high[]; // array for storing High prices of visible bars

// array for storing Low prices of visible bars

//--- number of visible bars in the chart window


int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{

2000-2016, MetaQuotes Software Corp.

543

Standard Constants, Enumerations and Structures


Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- define how often texts are to be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=12;
break;
case 1:
step=6;
break;
case 2:
step=4;
break;
case 3:
step=2;
break;
}
//--- create texts for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the texts

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

2000-2016, MetaQuotes Software Corp.

544

Standard Constants, Enumerations and Structures


if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete the texts
for(int i=0;i<bars;i+=step)
{
if(!TextDelete(0,"TextHigh_"+(string)i))
return;
if(!TextDelete(0,"TextLow_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--}

2000-2016, MetaQuotes Software Corp.

545

Standard Constants, Enumerations and Structures

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;

// Slope angle in degrees

input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER; // Anchor type

2000-2016, MetaQuotes Software Corp.

546

Standard Constants, Enumerations and Structures


input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

corner=CORNER_LEFT_UPPER, // chart corner for anchoring

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

const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type


const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

547

Standard Constants, Enumerations and Structures


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 label 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 text label

//+------------------------------------------------------------------+
bool LabelMove(const long

chart_ID=0,

// chart's ID

const string name="Label", // label name


const int

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

const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart corner for anchori


{
//--- reset the error value
ResetLastError();
//--- change anchor corner

2000-2016, MetaQuotes Software Corp.

548

Standard Constants, Enumerations and Structures


if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the label text

//+------------------------------------------------------------------+
bool LabelTextChange(const long

chart_ID=0,

// chart's ID

const string name="Label", // object name


const string text="Text")

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

const string name="Label") // label name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a text label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

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

2000-2016, MetaQuotes Software Corp.

549

Standard Constants, Enumerations and Structures


void OnStart()
{
//--- store the label's coordinates in the local variables
int x=InpX;
int y=InpY;
//--- 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;
}
//--- check correctness of the input parameters
if(InpX<0 || InpX>x_distance-1 || InpY<0 || InpY>y_distance-1)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- prepare initial text for the label
string text;
StringConcatenate(text,"Upper left corner: ",x,",",y);
//--- create a text label on the chart
if(!LabelCreate(0,InpName,0,InpX,InpY,CORNER_LEFT_UPPER,text,InpFont,InpFontSize,
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//--- move the label and change its text simultaneously
//--- number of iterations by axes
int h_steps=(int)(x_distance/2-InpX);
int v_steps=(int)(y_distance/2-InpY);
//--- move the label down
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}

2000-2016, MetaQuotes Software Corp.

550

Standard Constants, Enumerations and Structures


//--- half a second of delay
Sleep(500);
//--- move the label to the right
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label up
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label to the left
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- now, move the point by changing the anchor corner
//--- move to the lower left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_LOWER))
return;
//--- change the label text
StringConcatenate(text,"Lower left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the lower right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_LOWER))
return;
//--- change the label text
StringConcatenate(text,"Lower right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))

2000-2016, MetaQuotes Software Corp.

551

Standard Constants, Enumerations and Structures


return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_UPPER))
return;
//--- change the label text
StringConcatenate(text,"Upper right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_UPPER))
return;
//--- change the label text
StringConcatenate(text,"Upper left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- delete the label
LabelDelete(0,InpName);
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//--}
//+------------------------------------------------------------------+
//| The function moves the object and changes its text

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

552

Standard Constants, Enumerations and Structures


Sleep(10);
//--- exit the function
return(true);
}

2000-2016, MetaQuotes Software Corp.

553

Standard Constants, Enumerations and Structures

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

input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring


input string

InpFont="Arial";

// Font

input int

InpFontSize=14;

// Font size

input color

InpColor=clrBlack;

// Text color

input color

InpBackColor=C'236,233,216'; // Background 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

2000-2016, MetaQuotes Software Corp.

554

Standard Constants, Enumerations and Structures


input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

corner=CORNER_LEFT_UPPER, // chart corner for anchoring

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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

555

Standard Constants, Enumerations and Structures


ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- set button state
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- enable (true) or disable (false) the mode of moving the button 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 button

//+------------------------------------------------------------------+
bool ButtonMove(const long

chart_ID=0,

// chart's ID

const string name="Button", // button name


const int

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

2000-2016, MetaQuotes Software Corp.

556

Standard Constants, Enumerations and Structures


const string name="Button", // button name
const int

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

const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart corner for anchor


{
//--- reset the error value
ResetLastError();
//--- change anchor corner
if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button text

//+------------------------------------------------------------------+
bool ButtonTextChange(const long

chart_ID=0,

// chart's ID

const string name="Button", // button name


const string text="Text")

// text

{
//--- reset the error value

2000-2016, MetaQuotes Software Corp.

557

Standard Constants, Enumerations and Structures


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 the button

//+------------------------------------------------------------------+
bool ButtonDelete(const long

chart_ID=0,

// chart's ID

const string name="Button") // button name


{
//--- reset the error value
ResetLastError();
//--- delete the button
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the button! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

558

Standard Constants, Enumerations and Structures


int x_step=(int)x_distance/32;
int y_step=(int)y_distance/32;
//--- set the button coordinates and its size
int x=(int)x_distance/32;
int y=(int)y_distance/32;
int x_size=(int)x_distance*15/16;
int y_size=(int)y_distance*15/16;
//--- create the button
if(!ButtonCreate(0,InpName,0,x,y,x_size,y_size,InpCorner,"Press",InpFont,InpFontSize,
InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- reduce the button in the loop
int i=0;
while(i<13)
{
//--- half a second of delay
Sleep(500);
//--- switch the button to the pressed state
ObjectSetInteger(0,InpName,OBJPROP_STATE,true);
//--- redraw the chart and wait for 0.2 second
ChartRedraw();
Sleep(200);
//--- redefine coordinates and button size
x+=x_step;
y+=y_step;
x_size-=x_step*2;
y_size-=y_step*2;
//--- reduce the button
ButtonMove(0,InpName,x,y);
ButtonChangeSize(0,InpName,x_size,y_size);
//--- bring the button back to the released state
ObjectSetInteger(0,InpName,OBJPROP_STATE,false);
//--- redraw the chart
ChartRedraw();
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- increase the loop counter
i++;
}
//--- half a second of delay
Sleep(500);
//--- delete the button
ButtonDelete(0,InpName);
ChartRedraw();

2000-2016, MetaQuotes Software Corp.

559

Standard Constants, Enumerations and Structures


//--- wait for 1 second
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

560

Standard Constants, Enumerations and Structures

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

input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Anchoring corner


input int

InpScale=2;

// Scale

input bool

InpDateScale=true;

// Time scale display

input bool

InpPriceScale=true;

// Price scale display

2000-2016, MetaQuotes Software Corp.

561

Standard Constants, Enumerations and Structures


input color

InpColor=clrRed;

// Border color when highlighted

input ENUM_LINE_STYLE

InpStyle=STYLE_DASHDOTDOT;

// Line style when highlighted

input int

InpPointWidth=1;

// Point size to move

input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

corner=CORNER_LEFT_UPPER, // anchoring corner

const int

scale=2,

// scale

const bool

date_scale=true,

// time scale display

const bool

price_scale=true,

// price scale display

const color

clr=clrRed,

// border color when highl

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// line style when highlig

const int

point_width=1,

// move point size

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object li

const long

z_order=0)

// priority for mouse clic

{
//--- 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

2000-2016, MetaQuotes Software Corp.

562

Standard Constants, Enumerations and Structures


ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol);
//--- set the period
ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period);
//--- set the scale
ObjectSetInteger(chart_ID,name,OBJPROP_CHART_SCALE,scale);
//--- display (true) or hide (false) the time scale
ObjectSetInteger(chart_ID,name,OBJPROP_DATE_SCALE,date_scale);
//--- display (true) or hide (false) the price scale
ObjectSetInteger(chart_ID,name,OBJPROP_PRICE_SCALE,price_scale);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_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
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);
}
//+------------------------------------------------------------------+
//| Sets the symbol and time frame of the Chart object

//+------------------------------------------------------------------+
bool ObjectChartSetSymbolAndPeriod(const long

chart_ID=0,

// chart's ID (not Chart

const string

name="Chart",

// object name

const string

symbol="EURUSD",

// symbol

const ENUM_TIMEFRAMES period=PERIOD_H1) // time frame


{
//--- reset the error value
ResetLastError();
//--- set Chart object's symbol and time frame
if(!ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol))
{
Print(__FUNCTION__,
": failed to set a symbol for \"Chart\" object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period))
{
Print(__FUNCTION__,
": failed to set a period for \"Chart\" object! Error code = ",GetLastError());
return(false);

2000-2016, MetaQuotes Software Corp.

563

Standard Constants, Enumerations and Structures


}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Chart object

//+------------------------------------------------------------------+
bool ObjectChartMove(const long

chart_ID=0,

// chart's ID (not Chart object's one)

const string name="Chart", // object name


const int

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,

// chart's ID (not Chart object's one)

const string name="Chart", // object name


const int

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

2000-2016, MetaQuotes Software Corp.

564

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to change the height of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Return Chart object's ID

//+------------------------------------------------------------------+
long ObjectChartGetID(const long

chart_ID=0,

// chart's ID (not Chart object's one)

const string name="Chart") // object name


{
//--- prepare the variable to get Chart object's ID
long id=-1;
//--- reset the error value
ResetLastError();
//--- get ID
if(!ObjectGetInteger(chart_ID,name,OBJPROP_CHART_ID,0,id))
{
Print(__FUNCTION__,
": failed to get \"Chart\" object's ID! Error code = ",GetLastError());
}
//--- return the result
return(id);
}
//+------------------------------------------------------------------+
//| Delete Chart object

//+------------------------------------------------------------------+
bool ObjectChartDelete(const long

chart_ID=0,

// chart's ID (not Chart object's one)

const string name="Chart") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the button
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{

2000-2016, MetaQuotes Software Corp.

565

Standard Constants, Enumerations and Structures


//--- get the number of symbols in Market Watch
int

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

2000-2016, MetaQuotes Software Corp.

566

Standard Constants, Enumerations and Structures


Sleep(1000);
//--- stretch Chart object
int steps=(int)MathMin(x_distance*7/16,y_distance*7/16);
for(int i=0;i<steps;i++)
{
//--- resize
x_size+=1;
y_size+=1;
if(!ObjectChartChangeSize(0,InpName,x_size,y_size))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.01 seconds
ChartRedraw();
Sleep(10);
}
//--- half a second of delay
Sleep(500);
//--- change chart's time frame
if(!ObjectChartSetSymbolAndPeriod(0,InpName,InpSymbol,PERIOD_M1))
return;
ChartRedraw();
//--- three seconds of delay
Sleep(3000);
//--- delete the object
ObjectChartDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

567

Standard Constants, Enumerations and Structures

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

InpFile="\\Images\\dollar.bmp"; // Bitmap file name

input int

InpWidth=24;

// Visibility scope X coordinate

input int

InpHeight=24;

// Visibility scope Y coordinate

input int

InpXOffset=4;

// Visibility scope shift by X axis

input int

InpYOffset=4;

// Visibility scope shift by Y axis

input color

InpColor=clrRed;

// Border color when highlighted

input ENUM_LINE_STYLE InpStyle=STYLE_SOLID;

// Line style when highlighted

input int

InpPointWidth=1;

// Point size to move

input bool

InpBack=false;

// Background object

input bool

InpSelection=false;

// Highlight to move

2000-2016, MetaQuotes Software Corp.

568

Standard Constants, Enumerations and Structures


input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// anchor point time

double

price=0,

// anchor point price

const string

file="",

// bitmap file name

const int

width=10,

// visibility scope X coordinate

const int

height=10,

// visibility scope Y coordinate

const int

x_offset=0,

// visibility scope shift by X axis

const int

y_offset=0,

// visibility scope shift by Y axis

const color

clr=clrRed,

// border color when highlighted

const ENUM_LINE_STYLE style=STYLE_SOLID, // line style when highlighted


const int

point_width=1,

// move point size

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

569

Standard Constants, Enumerations and Structures


//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_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
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);
}
//+------------------------------------------------------------------+
//| Set a new image for the bitmap

//+------------------------------------------------------------------+
bool BitmapSetImage(const long

chart_ID=0,

// chart's ID

const string name="Bitmap", // bitmap name


const string file="")

// path to the file

{
//--- 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

const string name="Bitmap", // bitmap name


datetime

time=0,

// anchor point time

double

price=0)

// anchor point price

{
//--- if point position is not set, move it to the current bar having Bid price

2000-2016, MetaQuotes Software Corp.

570

Standard Constants, Enumerations and Structures


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 visibility scope (bitmap) size

//+------------------------------------------------------------------+
bool BitmapChangeSize(const long

chart_ID=0,

// chart's ID

const string name="Bitmap", // bitmap name


const int

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

const string name="Bitmap", // bitmap name


const int

x_offset=0,

// visibility scope X coordinate

const int

y_offset=0)

// visibility scope Y coordinate

2000-2016, MetaQuotes Software Corp.

571

Standard Constants, Enumerations and Structures


{
//--- reset the error value
ResetLastError();
//--- change the bitmap'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 a bitmap

//+------------------------------------------------------------------+
bool BitmapDelete(const long

chart_ID=0,

// chart's ID

const string name="Bitmap") // bitmap name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a bitmap! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values

//| for empty ones

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

2000-2016, MetaQuotes Software Corp.

572

Standard Constants, Enumerations and Structures


}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
datetime date[];
double

// array for storing dates of visible bars

close[]; // array for storing Close prices

//--- bitmap file name


string

file="\\Images\\dollar.bmp";

//--- number of visible bars in the chart window


int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(close,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;
}
//--- fill the array of Close prices
if(CopyClose(Symbol(),Period(),0,bars,close)==-1)
{
Print("Failed to copy the values of Close prices! Error code = ",GetLastError());
return;
}
//--- define how often the images should be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=27;
break;
case 1:
step=14;
break;
case 2:
step=7;
break;
case 3:
step=4;
break;
case 4:
step=2;
break;

2000-2016, MetaQuotes Software Corp.

573

Standard Constants, Enumerations and Structures


}
//--- create bitmaps for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the bitmaps

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

2000-2016, MetaQuotes Software Corp.

574

Standard Constants, Enumerations and Structures

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

InpFileOn="\\Images\\dollar.bmp"; // File name for On mode

// Label name

input string

InpFileOff="\\Images\\euro.bmp";

// File name for Off mode

input bool

InpState=false;

// Label pressed/released

input ENUM_BASE_CORNER

InpCorner=CORNER_LEFT_UPPER;

// Chart corner for anchoring

input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER;

// Anchor type

input color

// Border color when highlighted

InpColor=clrRed;

2000-2016, MetaQuotes Software Corp.

575

Standard Constants, Enumerations and Structures


input ENUM_LINE_STYLE

InpStyle=STYLE_SOLID;

// Line style when highlighted

input int

InpPointWidth=1;

// Point size to move

input bool

InpBack=false;

// Background object

input bool

InpSelection=false;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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="",

// image in Off mode

const int

width=0,

// visibility scope X coor

const int

height=0,

// visibility scope Y coor

const int

x_offset=10,

// visibility scope shift

const int

y_offset=10,

// visibility scope shift

const bool

state=false,

// pressed/released

const ENUM_BASE_CORNER

corner=CORNER_LEFT_UPPER, // chart corner for anchor

const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type


const color

clr=clrRed,

// border color when highl

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// line style when highlig

const int

point_width=1,

// move point size

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object li

const long

z_order=0)

// priority for mouse clic

{
//--- 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))
{

2000-2016, MetaQuotes Software Corp.

576

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to load the image for Off mode! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- 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
//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- define the label's status (pressed or released)
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_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
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);
}
//+------------------------------------------------------------------+
//| Set a new image for Bitmap label object

//+------------------------------------------------------------------+
bool BitmapLabelSetImage(const long

chart_ID=0,

// chart's ID

const string name="BmpLabel", // label name


const int

on_off=0,

const string file="")

// modifier (On or Off)


// path to the file

2000-2016, MetaQuotes Software Corp.

577

Standard Constants, Enumerations and Structures


{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,on_off,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Bitmap Label object

//+------------------------------------------------------------------+
bool BitmapLabelMove(const long

chart_ID=0,

// chart's ID

const string name="BmpLabel", // label name


const int

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

const string name="BmpLabel", // label name


const int

width=0,

// label width

const int

height=0)

// label height

{
//--- reset the error value
ResetLastError();

2000-2016, MetaQuotes Software Corp.

578

Standard Constants, Enumerations and Structures


//--- 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 coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapLabelMoveVisibleArea(const long

chart_ID=0,

// chart's ID

const string name="BmpLabel", // label name


const int

x_offset=0,

// visibility scope X coordinate

const int

y_offset=0)

// visibility scope Y coordinate

{
//--- 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

const string name="BmpLabel") // label name


{
//--- reset the error value

2000-2016, MetaQuotes Software Corp.

579

Standard Constants, Enumerations and Structures


ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Bitmap label\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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++)

2000-2016, MetaQuotes Software Corp.

580

Standard Constants, Enumerations and Structures


{
//--- change visibility scope size
width--;
height--;
if(!BitmapLabelChangeSize(0,InpName,width,height))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- change label's visibility scope coordinates in the loop
for(int i=0;i<2;i++)
{
//--- change visibility scope coordinates
x_offset++;
y_offset++;
if(!BitmapLabelMoveVisibleArea(0,InpName,x_offset,y_offset))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label
BitmapLabelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

581

Standard Constants, Enumerations and Structures

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;

// Text alignment type

input bool

InpReadOnly=false;

// Permission to edit

input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring


input color

InpColor=clrBlack;

// Text color

2000-2016, MetaQuotes Software Corp.

582

Standard Constants, Enumerations and Structures


input color

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;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring


const color

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,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

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

2000-2016, MetaQuotes Software Corp.

583

Standard Constants, Enumerations and Structures


//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the type of text alignment in the object
ObjectSetInteger(chart_ID,name,OBJPROP_ALIGN,align);
//--- enable (true) or cancel (false) read-only mode
ObjectSetInteger(chart_ID,name,OBJPROP_READONLY,read_only);
//--- set the chart's corner, relative to which object coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set text color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_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 label 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 Edit object

//+------------------------------------------------------------------+
bool EditMove(const long

chart_ID=0,

// chart's ID

const string name="Edit", // object name


const int

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

2000-2016, MetaQuotes Software Corp.

584

Standard Constants, Enumerations and Structures


//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Resize Edit object

//+------------------------------------------------------------------+
bool EditChangeSize(const long

chart_ID=0,

// chart's ID

const string name="Edit", // object name


const int

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

const string name="Edit", // object name


const string text="Text") // 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);
}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

585

Standard Constants, Enumerations and Structures


//| Return Edit object text

//+------------------------------------------------------------------+
bool EditTextGet(string
const long

&text,
chart_ID=0,

// text
// chart's ID

const string name="Edit") // object name


{
//--- reset the error value
ResetLastError();
//--- get object text
if(!ObjectGetString(chart_ID,name,OBJPROP_TEXT,0,text))
{
Print(__FUNCTION__,
": failed to get the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Edit object

//+------------------------------------------------------------------+
bool EditDelete(const long

chart_ID=0,

// chart's ID

const string name="Edit") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

586

Standard Constants, Enumerations and Structures


}
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 edit field
int x_step=(int)x_distance/64;
//--- set edit field coordinates and its size
int x=(int)x_distance/8;
int y=(int)y_distance/2;
int x_size=(int)x_distance/8;
int y_size=InpFontSize*2;
//--- store the text in the local variable
string text=InpText;
//--- create edit field
if(!EditCreate(0,InpName,0,x,y,x_size,y_size,InpText,InpFont,InpFontSize,InpAlign,InpReadOnly,
InpCorner,InpColor,InpBackColor,InpBorderColor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- stretch the edit field
while(x_size-x<x_distance*5/8)
{
//--- increase edit field's width
x_size+=x_step;
if(!EditChangeSize(0,InpName,x_size,y_size))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.05 seconds
ChartRedraw();
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- change the text
for(int i=0;i<20;i++)
{
//--- add "+" at the beginning and at the end
text="+"+text+"+";
if(!EditTextChange(0,InpName,text))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

2000-2016, MetaQuotes Software Corp.

587

Standard Constants, Enumerations and Structures


return;
//--- redraw the chart and wait for 0.1 seconds
ChartRedraw();
Sleep(100);
}
//--- half a second of delay
Sleep(500);
//--- delete edit field
EditDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

588

Standard Constants, Enumerations and Structures

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;

// Point size when highlighted

input bool

InpBack=false;

// Background event

input bool

InpSelection=false; // Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

2000-2016, MetaQuotes Software Corp.

589

Standard Constants, Enumerations and Structures


input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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,

// point width when highlighted

const bool

back=false,

// in the background

const bool

selection=false, // highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

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

2000-2016, MetaQuotes Software Corp.

590

Standard Constants, Enumerations and Structures


bool EventTextChange(const long

chart_ID=0,

// chart's ID

const string name="Event", // event name


const string text="Text")

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

const string name="Event", // event name


datetime

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

const string name="Event") // event name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{

2000-2016, MetaQuotes Software Corp.

591

Standard Constants, Enumerations and Structures


Print(__FUNCTION__,
": failed to delete \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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++)
{

2000-2016, MetaQuotes Software Corp.

592

Standard Constants, Enumerations and Structures


//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!EventMove(0,InpName,date[d]))
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);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
EventDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

593

Standard Constants, Enumerations and Structures

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

input ENUM_BORDER_TYPE InpBorder=BORDER_FLAT;

// Border type

input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring


input color

InpColor=clrDarkBlue;

// Flat border color (Flat)

input ENUM_LINE_STYLE

InpStyle=STYLE_SOLID;

// Flat border style (Flat)

input int

InpLineWidth=3;

// Flat border width (Flat)

2000-2016, MetaQuotes Software Corp.

594

Standard Constants, Enumerations and Structures


input bool

InpBack=false;

// Background object

input bool

InpSelection=true;

// Highlight to move

input bool

InpHidden=true;

// Hidden in the object list

input long

InpZOrder=0;

// Priority for mouse click

//+------------------------------------------------------------------+
//| 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

const ENUM_BORDER_TYPE border=BORDER_SUNKEN,

// border type

const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring


const color

clr=clrRed,

// flat border color (Flat)

const ENUM_LINE_STYLE

style=STYLE_SOLID,

// flat border style

const int

line_width=1,

// flat border width

const bool

back=false,

// in the background

const bool

selection=false,

// highlight to move

const bool

hidden=true,

// hidden in the object list

const long

z_order=0)

// priority for mouse click

{
//--- 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

2000-2016, MetaQuotes Software Corp.

595

Standard Constants, Enumerations and Structures


ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set flat border width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_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
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 rectangle label

//+------------------------------------------------------------------+
bool RectLabelMove(const long

chart_ID=0,

// chart's ID

const string name="RectLabel", // label name


const int

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

const string name="RectLabel", // label name


const int

width=50,

// label width

const int

height=18)

// label height

2000-2016, MetaQuotes Software Corp.

596

Standard Constants, Enumerations and Structures


//--- reset the error value
ResetLastError();
//--- change label size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the label's width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the label's height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change rectangle label border type

//+------------------------------------------------------------------+
bool RectLabelChangeBorderType(const long
const string

chart_ID=0,

// chart's ID

name="RectLabel",

// label name

const ENUM_BORDER_TYPE border=BORDER_SUNKEN) // border type


{
//--- reset the error value
ResetLastError();
//--- change border type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border))
{
Print(__FUNCTION__,
": failed to change the border type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle label

//+------------------------------------------------------------------+
bool RectLabelDelete(const long

chart_ID=0,

// chart's ID

const string name="RectLabel") // label name


{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,

2000-2016, MetaQuotes Software Corp.

597

Standard Constants, Enumerations and Structures


": failed to delete a rectangle label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
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;

2000-2016, MetaQuotes Software Corp.

598

Standard Constants, Enumerations and Structures


//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.01 seconds
ChartRedraw();
Sleep(10);
}
//--- 1 second of delay
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_RAISED))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_SUNKEN))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- delete the label
RectLabelDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//--}

2000-2016, MetaQuotes Software Corp.

599

Standard Constants, Enumerations and Structures

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

The following designations are used in the table:


X/Y coordinates of anchor points specified in pixels relative to a chart corner;
Width/Height objects have width and height. For "read only", the width and height values are

calculated only once the object is rendered on chart;


Date/Price anchor point coordinates are specified using the date and price values;
OBJPROP_CORNER defines the chart corner relative to which the anchor point coordinates are

specified. Can be one of the 4 values of the ENUM_BASE_CORNER enumeration;


OBJPROP_ANCHOR defines the anchor point in object itself and can be one of the 9 values of the

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.

2000-2016, MetaQuotes Software Corp.

600

Standard Constants, Enumerations and Structures


Generally, the graphical objects on the chart are updated automatically by the terminal following the
change events - a new quote arrival, resizing the chart window, etc. Use ChartRedraw() function to
forcefully update the graphical objects.
For functions ObjectSetInteger() and ObjectGetInteger()
ENUM_OBJECT_PROPERTY_INTEGER
Identifier

Description

Property Type

OBJPROP_COLOR

Color

color

OBJPROP_STYLE

Style

ENUM_LINE_STYLE

OBJPROP_WIDTH

Line thickness

int

OBJPROP_BACK

Object in the background

bool

OBJPROP_ZORDER

Priority of a graphical object


for receiving events of clicking
on
a
chart
(CHARTEVENT_CLICK).
The
default zero value is set when
creating an object; the priority
can be increased if necessary.
When objects are placed one
atop another, only one of them
with the highest priority will
receive
the
CHARTEVENT_CLICK event.

long

OBJPROP_FILL

Fill an object with color (for


OBJ_RECTANGLE,
OBJ_TRIANGLE, OBJ_ELLIPSE,
OBJ_CHANNEL,
OBJ_STDDEVCHANNEL,
OBJ_REGRESSION)

bool

OBJPROP_HIDDEN

Prohibit showing of the name


of a graphical object in the list
of objects from the terminal
menu "Charts" - "Objects" "List of objects". The true
value allows to hide an object
from the list. By default, true
is set to the objects that
display
calendar
events,
trading history and to the
objects created from MQL5
programs.
To
see
such
graphical objects and access
their properties, click on the
"All" button in the "List of
objects" window.

bool

2000-2016, MetaQuotes Software Corp.

601

Standard Constants, Enumerations and Structures


OBJPROP_SELECTED

Object is selected

bool

OBJPROP_READONLY

Ability to edit text in the Edit


object

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

Time of object creation

datetime

OBJPROP_LEVELS

Number of levels

int

OBJPROP_LEVELCOLOR

Color of the line-level

color modifier=level number

OBJPROP_LEVELSTYLE

Style of the line-level

ENUM_LINE_STYLE
modifier=level number

OBJPROP_LEVELWIDTH

Thickness of the line-level

int

r/o

modifier=level number

OBJPROP_ALIGN

Horizontal text alignment in


the "Edit" object (OBJ_EDIT)

ENUM_ALIGN_MODE

OBJPROP_FONTSIZE

Font size

int

OBJPROP_RAY_LEFT

Ray goes to the left

bool

OBJPROP_RAY_RIGHT

Ray goes to the right

bool

OBJPROP_RAY

A vertical line goes through all


the windows of a chart

bool

OBJPROP_ELLIPSE

Showing the full ellipse of the


Fibonacci
Arc
object
(OBJ_FIBOARC)

bool

OBJPROP_ARROWCODE

Arrow code
object

char

OBJPROP_TIMEFRAMES

Visibility of
timeframes

OBJPROP_ANCHOR

Location of the anchor point of


a graphical object

for the

an

Arrow

object

at

set of flags flags

ENUM_ARROW_ANCHOR
OBJ_ARROW),
ENUM_ANCHOR_POINT
OBJ_LABEL,
OBJ_BITMAP_LABEL
OBJ_TEXT)

OBJPROP_XDISTANCE

The distance in pixels along the


X axis from the binding corner
(see note)

int

OBJPROP_YDISTANCE

The distance in pixels along the


Y axis from the binding corner
(see note)

int

2000-2016, MetaQuotes Software Corp.

(for
(for
and

602

Standard Constants, Enumerations and Structures


OBJPROP_DIRECTION

Trend of the Gann object

OBJPROP_DEGREE

Level of
Marking

OBJPROP_DRAWLINES

Displaying lines for marking the


Elliott Wave

bool

OBJPROP_STATE

Button state
depressed)

bool

OBJPROP_CHART_ID

ID of the "Chart" object


(OBJ_CHART).
It
allows
working with the properties of
this object like with a normal
chart using the functions
described in Chart Operations,
but there some exceptions.

long r/o

OBJPROP_XSIZE

The object's width along the X


axis in pixels. Specified for
OBJ_LABEL
(read
only),
OBJ_BUTTON,
OBJ_CHART,
OBJ_BITMAP,
OBJ_BITMAP_LABEL, OBJ_EDIT,
OBJ_RECTANGLE_LABEL
objects.

int

OBJPROP_YSIZE

The object's height along the Y


axis in pixels. Specified for
OBJ_LABEL
(read
only),
OBJ_BUTTON,
OBJ_CHART,
OBJ_BITMAP,
OBJ_BITMAP_LABEL, OBJ_EDIT,
OBJ_RECTANGLE_LABEL
objects.

int

OBJPROP_XOFFSET

The X coordinate of the upper


left corner of the rectangular
visible area in the graphical
objects "Bitmap Label" and
"Bitmap" (OBJ_BITMAP_LABEL
and OBJ_BITMAP). The value is
set in pixels relative to the
upper left corner of the original
image.

int

OBJPROP_YOFFSET

The Y coordinate of the upper


left corner of the rectangular
visible area in the graphical
objects "Bitmap Label" and
"Bitmap" (OBJ_BITMAP_LABEL
and OBJ_BITMAP). The value is
set in pixels relative to the

int

the

Elliott

ENUM_GANN_DIRECTION
Wave

(pressed

2000-2016, MetaQuotes Software Corp.

ENUM_ELLIOT_WAVE_DEGREE

603

Standard Constants, Enumerations and Structures


upper left corner of the original
image.
OBJPROP_PERIOD

Timeframe
object

for

the

Chart

ENUM_TIMEFRAMES

OBJPROP_DATE_SCALE

Displaying the time scale for


the Chart object

bool

OBJPROP_PRICE_SCALE

Displaying the price scale for


the Chart object

bool

OBJPROP_CHART_SCALE

The scale for the Chart object

int value in the range 05

OBJPROP_BGCOLOR

The background color for


OBJ_EDIT,
OBJ_BUTTON,
OBJ_RECTANGLE_LABEL

color

OBJPROP_CORNER

The corner of the chart to link


a graphical object

ENUM_BASE_CORNER

OBJPROP_BORDER_TYPE

Border type for the "Rectangle


label" object

ENUM_BORDER_TYPE

OBJPROP_BORDER_COLOR

Border color for the OBJ_EDIT


and OBJ_BUTTON objects

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.

For the fixed-sized objects: OBJ_BUTTON, OBJ_RECTANGLE_LABEL, OBJ_EDIT and OBJ_CHART,


properties OBJPROP_XDISTANCE and OBJPROP_YDISTANCE set the position of the top left point of the
object relative to the chart corner (OBJPROP_CORNER), from which the X and Y coordinates will be
counted in pixels.

For functions ObjectSetDouble() and ObjectGetDouble()


ENUM_OBJECT_PROPERTY_DOUBLE

2000-2016, MetaQuotes Software Corp.

604

Standard Constants, Enumerations and Structures


Identifier

Description

Property Type

OBJPROP_PRICE

Price coordinate

double
modifier=number of
anchor point

OBJPROP_LEVELVALUE

Level value

double

OBJPROP_SCALE

Scale (properties of Gann


objects and Fibonacci Arcs)

double

OBJPROP_ANGLE

Angle. For the objects with no


angle specified, created from a
program, the value is equal to
EMPTY_VALUE

double

OBJPROP_DEVIATION

Deviation for the


Deviation Channel

double

Standard

modifier=level number

For functions ObjectSetString() and ObjectGetString()


ENUM_OBJECT_PROPERTY_STRING
Identifier

Description

Property Type

OBJPROP_NAME

Object name

string

OBJPROP_TEXT

Description of the object (the


text contained in the object)

string

OBJPROP_TOOLTIP

The text of a tooltip. If the


property is not set, then the
tooltip generated automatically
by the terminal is shown. A
tooltip can be disabled by
setting the "\n" (line feed)
value to it

string

OBJPROP_LEVELTEXT

Level description

string

OBJPROP_FONT

Font

string

OBJPROP_BMPFILE

The name of BMP-file for


Bitmap
Label.
See
also
Resources

string
modifier: 0-state ON,
1-state OFF

OBJPROP_SYMBOL

Symbol for the Chart object

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

2000-2016, MetaQuotes Software Corp.

605

Standard Constants, Enumerations and Structures


BORDER_FLAT

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

Centered (only for the Edit object)

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

2000-2016, MetaQuotes Software Corp.

606

Standard Constants, Enumerations and Structures


//--- draw it on the chart
ChartRedraw(0);
}
}

2000-2016, MetaQuotes Software Corp.

607

Standard Constants, Enumerations and Structures

Methods of Object Binding


Graphical objects Text, Label, Bitmap and Bitmap Label (OBJ_TEXT, OBJ_LABEL, OBJ_BITMAP and
OBJ_BITMAP_LABEL) can have one of the 9 different ways of coordinate binding defined by the
OBJPROP_ANCHOR property.
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

The following designations are used in the table:


X/Y coordinates of anchor points specified in pixels relative to a chart corner;
Width/Height objects have width and height. For "read only", the width and height values are

calculated only once the object is rendered on chart;


Date/Price anchor point coordinates are specified using the date and price values;
OBJPROP_CORNER defines the chart corner relative to which the anchor point coordinates are

specified. Can be one of the 4 values of the ENUM_BASE_CORNER enumeration;


OBJPROP_ANCHOR defines the anchor point in object itself and can be one of the 9 values of the

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 necessary variant can be specified using the function ObjectSetInteger(chart_handle,


object_name, OBJPROP_ANCHOR, anchor_point_mode), where anchor_point_mode is one of the
values of ENUM_ANCHOR_POINT.
ENUM_ANCHOR_POINT
ID
ANCHOR_LEFT_UPPER

Description
Anchor point at the upper left corner

2000-2016, MetaQuotes Software Corp.

608

Standard Constants, Enumerations and Structures


ANCHOR_LEFT

Anchor point to the left in the center

ANCHOR_LEFT_LOWER

Anchor point at the lower left corner

ANCHOR_LOWER

Anchor point below in the center

ANCHOR_RIGHT_LOWER

Anchor point at the lower right corner

ANCHOR_RIGHT

Anchor point to the right in the center

ANCHOR_RIGHT_UPPER

Anchor point at the upper right corner

ANCHOR_UPPER

Anchor point above in the center

ANCHOR_CENTER

Anchor point strictly in the center of the object

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

2000-2016, MetaQuotes Software Corp.

609

Standard Constants, Enumerations and Structures


ID

Description

ANCHOR_TOP

Anchor on the top side

ANCHOR_BOTTOM

Anchor on the bottom side

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

2000-2016, MetaQuotes Software Corp.

610

Standard Constants, Enumerations and Structures


for(int i=2;i<copied;i++)// Run through the values of the indicator iFractals
{
if(Ups[i]!=EMPTY_VALUE)// Found the upper fractal
{
if(upcounter<10)// Create no more than 10 "Up" arrows
{
//--- Try to create an "Up" object
created=ObjectCreate(0,string(Time[i]),OBJ_ARROW_THUMB_UP,0,Time[i],Ups[i]);
if(created)// If set up - let's make tuning for it
{
//--- Point anchor is below in order not to cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_BOTTOM);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,clrBlue);
upcounter++;
}
}
}
if(Downs[i]!=EMPTY_VALUE)// Found a lower fractal
{
if(downcounter<10)// Create no more than 10 arrows "Down"
{
//--- Try to create an object "Down"
created=ObjectCreate(0,string(Time[i]),OBJ_ARROW_THUMB_DOWN,0,Time[i],Downs[i]);
if(created)// If set up - let's make tuning for it
{
//--- Point anchor is above in order not to cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_TOP);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,clrRed);
downcounter++;
}
}
}
}
}

After the script execution the chart will look like in this figure.

2000-2016, MetaQuotes Software Corp.

611

Standard Constants, Enumerations and Structures

2000-2016, MetaQuotes Software Corp.

612

Standard Constants, Enumerations and Structures

The Chart Corner to Which an Object Is Attached


There is a number of graphical objects for which you can set a chart corner, relative to which the
coordinates are specified in pixels. These are the following types of objects (in brackets object type
identifiers are specified):
Label (OBJ_LABEL);
Button (OBJ_BUTTON);
Bitmap Label (OBJ_BITMAP_LABEL);
Edit (OBJ_EDIT).
Rectangle Label (OBJ_RECTANGLE_LABEL);

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

The following designations are used in the table:


X/Y coordinates of anchor points specified in pixels relative to a chart corner;
Width/Height objects have width and height. For "read only", the width and height values are

calculated only once the object is rendered on chart;


Date/Price anchor point coordinates are specified using the date and price values;
OBJPROP_CORNER defines the chart corner relative to which the anchor point coordinates are

specified. Can be one of the 4 values of the ENUM_BASE_CORNER enumeration;


OBJPROP_ANCHOR defines the anchor point in object itself and can be one of the 9 values of the

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:

2000-2016, MetaQuotes Software Corp.

613

Standard Constants, Enumerations and Structures


chartID - chart identifier;
name name of a graphical object;
OBJPROP_CORNER property ID to specify the corner for binding;
chart_corner the desired chart corner, can be one of the values of the ENUM_BASE_CORNER

enumeration.
ENUM_BASE_CORNER
ID

Description

CORNER_LEFT_UPPER

Center of coordinates is in the upper left corner


of the chart

CORNER_LEFT_LOWER

Center of coordinates is in the lower left corner


of the chart

CORNER_RIGHT_LOWER

Center of coordinates is in the lower right corner


of the chart

CORNER_RIGHT_UPPER

Center of coordinates is in the upper right


corner of the chart

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

2000-2016, MetaQuotes Software Corp.

614

Standard Constants, Enumerations and Structures


int width=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
string arrows[4]={"LEFT_UPPER","RIGHT_UPPER","RIGHT_LOWER","LEFT_LOWER"};
CreateLabel(0,arrows[0],CORNER_LEFT_UPPER,ANCHOR_LEFT_UPPER,arrows[0],50,50);
CreateLabel(0,arrows[1],CORNER_RIGHT_UPPER,ANCHOR_RIGHT_UPPER,arrows[1],50,50);
CreateLabel(0,arrows[2],CORNER_RIGHT_LOWER,ANCHOR_RIGHT_LOWER,arrows[2],50,50);
CreateLabel(0,arrows[3],CORNER_LEFT_LOWER,ANCHOR_LEFT_LOWER,arrows[3],50,50);
}

2000-2016, MetaQuotes Software Corp.

615

Standard Constants, Enumerations and Structures

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

The object is not drawn in all


timeframes

OBJ_PERIOD_M1

0x00000001

The object is drawn in 1minute chart

OBJ_PERIOD_M2

0x00000002

The object is drawn in 2minute chart

OBJ_PERIOD_M3

0x00000004

The object is drawn in 3minute chart

OBJ_PERIOD_M4

0x00000008

The object is drawn in 4minute chart

OBJ_PERIOD_M5

0x00000010

The object is drawn in 5minute chart

OBJ_PERIOD_M6

0x00000020

The object is drawn in 6minute chart

OBJ_PERIOD_M10

0x00000040

The object is drawn in 10minute chart

OBJ_PERIOD_M12

0x00000080

The object is drawn in 12minute chart

OBJ_PERIOD_M15

0x00000100

The object is drawn in 15minute chart

OBJ_PERIOD_M20

0x00000200

The object is drawn in 20minute chart

OBJ_PERIOD_M30

0x00000400

The object is drawn in 30minute chart

OBJ_PERIOD_H1

0x00000800

The object is drawn in 1-hour


chart

OBJ_PERIOD_H2

0x00001000

The object is drawn in 2-hour


chart

OBJ_PERIOD_H3

0x00002000

The object is drawn in 3-hour


chart

OBJ_PERIOD_H4

0x00004000

The object is drawn in 4-hour


chart

OBJ_PERIOD_H6

0x00008000

The object is drawn in 6-hour


chart

2000-2016, MetaQuotes Software Corp.

616

Standard Constants, Enumerations and Structures


OBJ_PERIOD_H8

0x00010000

The object is drawn in 8-hour


chart

OBJ_PERIOD_H12

0x00020000

The object is drawn in 12-hour


chart

OBJ_PERIOD_D1

0x00040000

The object is drawn in day


charts

OBJ_PERIOD_W1

0x00080000

The object is drawn in week


charts

OBJ_PERIOD_MN1

0x00100000

The object is drawn in month


charts

OBJ_ALL_PERIODS

0x001fffff

The object is drawn in all


timeframes

Visibility flags can be combined using the symbol "|", for example, the combination of flags
OBJ_PERIOD_M10|OBJ_PERIOD_H4 means that the object will be visible on the 10-minute and 4-hour
timeframes.
Example:
void OnStart()
{
//--string highlevel="PreviousDayHigh";
string lowlevel="PreviousDayLow";
double prevHigh;

// The previous day High

double prevLow;

// The previous day Low

double highs[],lows[];

// Arrays for High and Low

//--- Reset the last error


ResetLastError();
//--- Get the last 2 High values on the daily timeframe
int highsgot=CopyHigh(Symbol(),PERIOD_D1,0,2,highs);
if(highsgot>0) // If copying was successful
{
Print("High prices for the last 2 days were obtained successfully");
prevHigh=highs[0]; // The previous day High
Print("prevHigh = ",prevHigh);
if(ObjectFind(0,highlevel)<0) // Object with the name highlevel not found
{
ObjectCreate(0,highlevel,OBJ_HLINE,0,0,0); // Create the Horizontal Line object
}
//--- Set value for the price level for the line highlevel
ObjectSetDouble(0,highlevel,OBJPROP_PRICE,0,prevHigh);
//--- Set the visibility only PERIOD_M10 and PERIOD_H4
ObjectSetInteger(0,highlevel,OBJPROP_TIMEFRAMES,OBJ_PERIOD_M10|OBJ_PERIOD_H4);
}
else

2000-2016, MetaQuotes Software Corp.

617

Standard Constants, Enumerations and Structures


{
Print("Could not get High prices over the past 2 days, Error = ",GetLastError());
}
//--- Reset the last error
ResetLastError();
//--- Get the 2 days values Low on the daily timeframe
int lowsgot=CopyLow(Symbol(),PERIOD_D1,0,2,lows);
if(lowsgot>0) // If copying was successful
{
Print("Low prices for the last 2 days were obtained successfully");
prevLow=lows[0]; // The previous day Low
Print("prevLow = ",prevLow);
if(ObjectFind(0,lowlevel)<0) // Object with the name lowlevel not found
{
ObjectCreate(0,lowlevel,OBJ_HLINE,0,0,0); // Create the Horizontal Line object
}
//--- Set value for the price level for the line lowlevel
ObjectSetDouble(0,lowlevel,OBJPROP_PRICE,0,prevLow);
//--- Set the visibility only PERIOD_M10 and PERIOD_H4
ObjectSetInteger(0,lowlevel,OBJPROP_TIMEFRAMES,OBJ_PERIOD_M10|OBJ_PERIOD_H4);
}
else Print("Could not get Low prices for the last 2 days, Error = ",GetLastError());
ChartRedraw(0); // redraw the chart forcibly
}

See also
PeriodSeconds, Period, Chart timeframes, Date and Time

2000-2016, MetaQuotes Software Corp.

618

Standard Constants, Enumerations and Structures

Levels of Elliott Wave


Elliott Waves are represented by two graphical objects of types OBJ_ELLIOTWAVE5 and
OBJ_ELLIOTWAVE3. To set the wave size (method of wave labeling), the OBJPROP_DEGREE property is
used, to which one of values of the ENUM_ELLIOT_WAVE_DEGREE enumeration can be assigned.
ENUM_ELLIOT_WAVE_DEGREE
ID

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

2000-2016, MetaQuotes Software Corp.

619

Standard Constants, Enumerations and Structures

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

Line corresponding to the uptrend line

GANN_DOWN_TREND

Line corresponding to the downward 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.

Example of creating Gann Fan:


void OnStart()
{
//--string my_gann="OBJ_GANNFAN object";
if(ObjectFind(0,my_gann)<0)// Object not found
{
//--- Inform about the failure
Print("Object ",my_gann," not found. Error code = ",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Get the minimal price of the chart
double chart_min_price=ChartGetDouble(0,CHART_PRICE_MIN,0);
//--- How many bars are shown in the chart?

2000-2016, MetaQuotes Software Corp.

620

Standard Constants, Enumerations and Structures


int bars_on_chart=ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- Create an array, to write the opening time of each bar to
datetime Time[];
//--- Arrange access to the array as that of timeseries
ArraySetAsSeries(Time,true);
//--- Now copy data of bars visible in the chart into this array
int times=CopyTime(NULL,0,0,bars_on_chart,Time);
if(times<=0)
{
Print("Could not copy the array with the open time!");
return;
}
//--- Preliminary preparations completed
//--- Index of the central bar in the chart
int center_bar=bars_on_chart/2;
//--- Chart equator - between the maximum and minimum
double mean=(chart_max_price+chart_min_price)/2.0;
//--- Set the coordinates of the first anchor point to the center
ObjectCreate(0,my_gann,OBJ_GANNFAN,0,Time[center_bar],mean,
//--- Second anchor point to the right
Time[center_bar/2],(mean+chart_min_price)/2.0);
Print("Time[center_bar] = "+(string)Time[center_bar]+"
//Print("Time[center_bar]/="+Time[center_bar]+"

Time[center_bar/2] = "+(string)Time[c

Time[center_bar/2]="+Time[center_bar/2]);

//--- Set the scale in units of Pips / Bar


ObjectSetDouble(0,my_gann,OBJPROP_SCALE,10);
//--- Set the line trend
ObjectSetInteger(0,my_gann,OBJPROP_DIRECTION,GANN_UP_TREND);
//--- Set the line width
ObjectSetInteger(0,my_gann,OBJPROP_WIDTH,1);
//--- Define the line style
ObjectSetInteger(0,my_gann,OBJPROP_STYLE,STYLE_DASHDOT);
//--- Set the line color
ObjectSetInteger(0,my_gann,OBJPROP_COLOR,clrYellowGreen);
//--- Allow the user to select an object
ObjectSetInteger(0,my_gann,OBJPROP_SELECTABLE,true);
//--- Select it yourself
ObjectSetInteger(0,my_gann,OBJPROP_SELECTED,true);
//--- Draw it on the chart
ChartRedraw(0);
}
}

2000-2016, MetaQuotes Software Corp.

621

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

622

Standard Constants, Enumerations and Structures


Example:
//---- indicator settings
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots

#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

2000-2016, MetaQuotes Software Corp.

623

Standard Constants, Enumerations and Structures

Wingdings
Characters of Wingdings used with the OBJ_ARROW object:

A necessary character can be set using the ObjectSetInteger() function.


Example:
void OnStart()
{
//--string up_arrow="up_arrow";
datetime time=TimeCurrent();
double lastClose[1];
int close=CopyClose(Symbol(),Period(),0,1,lastClose);

// Get the Close price

//--- If the price was obtained


if(close>0)
{
ObjectCreate(0,up_arrow,OBJ_ARROW,0,0,0,0,0);

// Create an arrow

ObjectSetInteger(0,up_arrow,OBJPROP_ARROWCODE,241);

// Set the arrow code

ObjectSetInteger(0,up_arrow,OBJPROP_TIME,time);

// Set time

ObjectSetDouble(0,up_arrow,OBJPROP_PRICE,lastClose[0]);// Set price


ChartRedraw(0);

// Draw arrow now

}
else
Print("Unable to get the latest Close price!");
}

2000-2016, MetaQuotes Software Corp.

624

Standard Constants, Enumerations and Structures

Indicators Constants
There are 37 predefined technical indicators, which can be used in programs written in the MQL5
language. In addition, there is an opportunity to create custom indicators using the iCustom()
function. All constants required for that are divided into 5 groups:
Price constants for selecting the type of price or volume, on which an indicator is calculated;
Smoothing methods built-in smoothing methods used in indicators;
Indicator lines identifiers of indicator buffers when accessing indicator values using CopyBuffer();
Drawing styles for indicating one of 18 types of drawing and setting the line drawing style;
Custom indicators properties are used in functions for working with custom indicators;
Types of indicators are used for specifying the type of technical indicator when creating a handle

using IndicatorCreate();
Identifiers of data types are used for specifying the type of data passed in an array of the MqlParam

type into the IndicatorCreate() function.

2000-2016, MetaQuotes Software Corp.

625

Standard Constants, Enumerations and Structures

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

The maximum price for the period

PRICE_LOW

The minimum price for the period

PRICE_MEDIAN

Median price, (high + low)/2

PRICE_TYPICAL

Typical price, (high + low + close)/3

PRICE_WEIGHTED

Average price, (high + low + close + close)/4

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

The iStochastic() technical Indicator can be calculated in two ways using:


either only Close prices;
or High and Low prices.

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

Calculation is based on Low/High prices

STO_CLOSECLOSE

Calculation is based on Close/Close prices

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.

2000-2016, MetaQuotes Software Corp.

626

Standard Constants, Enumerations and Structures


Example:
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots

//--- input parameters


input int

RSIperiod=14;

// Period for calculating the RSI

input int

Smooth=8;

// Smoothing period RSI

input ENUM_MA_METHOD meth=MODE_SMMA; // Method of smoothing


//---- plot RSI
#property indicator_label1

"RSI"

#property indicator_type1

DRAW_LINE

#property indicator_color1

clrRed

#property indicator_style1

STYLE_SOLID

#property indicator_width1

//---- plot RSI_Smoothed


#property indicator_label2

"RSI_Smoothed"

#property indicator_type2

DRAW_LINE

#property indicator_color2

clrNavy

#property indicator_style2

STYLE_SOLID

#property indicator_width2

//--- indicator buffers


double

RSIBuffer[];

// Here we store the values of RSI

double

RSI_SmoothedBuffer[]; // Here will be smoothed values of RSI

int

RSIhandle;

// Handle to the RSI indicator

//+------------------------------------------------------------------+
//| Custom indicator initialization function

//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,RSIBuffer,INDICATOR_DATA);
SetIndexBuffer(1,RSI_SmoothedBuffer,INDICATOR_DATA);
IndicatorSetString(INDICATOR_SHORTNAME,"iRSI");
IndicatorSetInteger(INDICATOR_DIGITS,2);
//--RSIhandle=iRSI(NULL,0,RSIperiod,PRICE_CLOSE);
//--}
//+------------------------------------------------------------------+
//| Custom indicator iteration function

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[]
)
{

2000-2016, MetaQuotes Software Corp.

627

Standard Constants, Enumerations and Structures


//---

Reset the value of the last error

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

2000-2016, MetaQuotes Software Corp.

628

Standard Constants, Enumerations and Structures

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;

//--- get MA's handles


ExtJawsHandle=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtTeethHandle=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtLipsHandle=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN);

2000-2016, MetaQuotes Software Corp.

629

Standard Constants, Enumerations and Structures

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

Identifiers of indicator lines permissible when copying values of iBands().


Constant

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

Identifiers of indicator lines permissible when copying values of iGator()


Constant

Value

Description

UPPER_HISTOGRAM

Upper histogram

LOWER_HISTOGRAM

Bottom histogram

Identifiers of indicator lines permissible when copying values of iAlligator().


Constant

Value

2000-2016, MetaQuotes Software Corp.

Description

630

Standard Constants, Enumerations and Structures


GATORJAW_LINE

Jaw line

GATORTEETH_LINE

Teeth line

GATORLIPS_LINE

Lips line

Identifiers of indicator lines permissible when copying values of iIchimoku().


Constant

Value

Description

TENKANSEN_LINE

Tenkan-sen line

KIJUNSEN_LINE

Kijun-sen line

SENKOUSPANA_LINE

Senkou Span A line

SENKOUSPANB_LINE

Senkou Span B line

CHIKOUSPAN_LINE

Chikou Span line

2000-2016, MetaQuotes Software Corp.

631

Standard Constants, Enumerations and Structures

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

Histogram of the two


indicator buffers

DRAW_ARROW

Drawing arrows

DRAW_ZIGZAG

Style Zigzag allows


vertical section on the
bar

DRAW_FILLING

Color fill between the


two levels

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

2000-2016, MetaQuotes Software Corp.

632

Standard Constants, Enumerations and Structures


DRAW_COLOR_ARRO
W

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

Vertical shift of arrows for style


DRAW_ARROW

int

PLOT_DRAW_BEGIN

Number of initial bars without


drawing and values in the
DataWindow

int

PLOT_DRAW_TYPE

Type of graphical construction

ENUM_DRAW_TYPE

PLOT_SHOW_DATA

Sign of display of construction


values in the DataWindow

bool

PLOT_SHIFT

Shift of indicator plotting along


the time axis in bars

int

PLOT_LINE_STYLE

Drawing line style

ENUM_LINE_STYLE

PLOT_LINE_WIDTH

The thickness of the drawing


line

int

PLOT_COLOR_INDEXES

The number of colors

int

PLOT_LINE_COLOR

The index of a
buffer
containing the drawing color

color
modifier = index
number of colors

For the function PlotIndexSetDouble()


ENUM_PLOT_PROPERTY_DOUBLE
ID
PLOT_EMPTY_VALUE

Description
An empty value for plotting, for
which there is no drawing

2000-2016, MetaQuotes Software Corp.

Property type
double

633

Standard Constants, Enumerations and Structures


For the function PlotIndexSetString()
ENUM_PLOT_PROPERTY_STRING
ID

Description

PLOT_LABEL

Property type

The name of the indicator


graphical series to display in
the
DataWindow.
When
working with complex graphical
styles
requiring
several
indicator buffers for display,
the names for each buffer can
be specified using ";" as a
separator. Sample code is
shown in DRAW_CANDLES

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

Dash - two points

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

//--- indicator buffers


double

MABuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function

//+------------------------------------------------------------------+
void OnInit()
{
//--- Bind the Array to the indicator buffer with index 0
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
//--- Set the line drawing

2000-2016, MetaQuotes Software Corp.

634

Standard Constants, Enumerations and Structures


PlotIndexSetInteger(0,PLOT_DRAW_TYPE,DRAW_LINE);
//--- Set the style line
PlotIndexSetInteger(0,PLOT_LINE_STYLE,STYLE_DOT);
//--- Set line color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrRed);
//--- Set line thickness
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
//--- Set labels for the line
PlotIndexSetString(0,PLOT_LABEL,"Moving Average");
//--}
//+------------------------------------------------------------------+
//| Custom indicator iteration function

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--for(int i=prev_calculated;i<rates_total;i++)
{
MABuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}

2000-2016, MetaQuotes Software Corp.

635

Standard Constants, Enumerations and Structures

Custom Indicators Properties


The number of indicator buffers that can be used in a custom indicator is unlimited. But for each
array, which is designated as the indicator buffer using the SetIndexBuffer() function, it's necessary to
specify the data type that it will store. This may be one of the values of the ENUM_INDEXBUFFER_TYPE
enumeration.
ENUM_INDEXBUFFER_TYPE
ID

Description

INDICATOR_DATA

Data to draw

INDICATOR_COLOR_INDEX

Color

INDICATOR_CALCULATIONS

Auxiliary buffers for intermediate 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

Fixed height of the indicator's


window
(the
preprocessor
command
#property
indicator_height)

int

INDICATOR_LEVELS

Number of levels
indicator window

int

INDICATOR_LEVELCOLOR

Color of the level line

color
level number

INDICATOR_LEVELSTYLE

Style of the level line

ENUM_LINE_STYLE modifier =
level number

INDICATOR_LEVELWIDTH

Thickness of the level line

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

2000-2016, MetaQuotes Software Corp.

modifier =

modifier =

636

Standard Constants, Enumerations and Structures


INDICATOR_LEVELVALUE

Level value

double
level number

modifier =

ENUM_CUSTOMIND_PROPERTY_STRING
ID

Description

Property type

INDICATOR_SHORTNAME

Short indicator name

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

//--- input parameters


extern int KPeriod=5;
extern int DPeriod=3;
extern int Slowing=3;
//--- indicator buffers
double MainBuffer[];
double SignalBuffer[];
double HighesBuffer[];
double LowesBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function

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

2000-2016, MetaQuotes Software Corp.

637

Standard Constants, Enumerations and Structures


//--- sets first bar from which index will be drawn
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,KPeriod+Slowing-2);
PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,KPeriod+Slowing+DPeriod);
//--- set style STYLE_DOT for second line
PlotIndexSetInteger(1,PLOT_LINE_STYLE,STYLE_DOT);
//--- name for DataWindow and indicator subwindow label
IndicatorSetString(INDICATOR_SHORTNAME,"Stoch("+KPeriod+","+DPeriod+","+Slowing+")");
PlotIndexSetString(0,PLOT_LABEL,"Main");
PlotIndexSetString(1,PLOT_LABEL,"Signal");
//--- sets drawing line to empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0.0);
//--- initialization done
}

2000-2016, MetaQuotes Software Corp.

638

Standard Constants, Enumerations and Structures

Types of Technical Indicators


There are two ways to create an indicator handle for further accessing to its values. The first way is to
directly specify a function name from the list of technical indicators. The second method using the
IndicatorCreate() is to uniformly create a handle of any indicator by assigning an identifier from the
ENUM_INDICATOR enumeration. Both ways of handle creation are equal, you can use the one that is
most convenient in a particular case when writing a program in MQL5.
When creating an indicator of type IND_CUSTOM, the type field of the first element of an array of
input parameters MqlParam must have the TYPE_STRING value of the enumeration ENUM_DATATYPE,
while the field string_value of the first element must contain the name of the custom indicator.
ENUM_INDICATOR
Identifier

Indicator

IND_AC

Accelerator Oscillator

IND_AD

Accumulation/Distribution

IND_ADX

Average Directional Index

IND_ADXW

ADX by Welles Wilder

IND_ALLIGATOR

Alligator

IND_AMA

Adaptive Moving Average

IND_AO

Awesome Oscillator

IND_ATR

Average True Range

IND_BANDS

Bollinger Bands

IND_BEARS

Bears Power

IND_BULLS

Bulls Power

IND_BWMFI

Market Facilitation Index

IND_CCI

Commodity Channel Index

IND_CHAIKIN

Chaikin Oscillator

IND_CUSTOM

Custom indicator

IND_DEMA

Double Exponential Moving Average

IND_DEMARKER

DeMarker

IND_ENVELOPES

Envelopes

IND_FORCE

Force Index

IND_FRACTALS

Fractals

IND_FRAMA

Fractal Adaptive Moving Average

IND_GATOR

Gator Oscillator

IND_ICHIMOKU

Ichimoku Kinko Hyo

2000-2016, MetaQuotes Software Corp.

639

Standard Constants, Enumerations and Structures


IND_MA

Moving Average

IND_MACD

MACD

IND_MFI

Money Flow Index

IND_MOMENTUM

Momentum

IND_OBV

On Balance Volume

IND_OSMA

OsMA

IND_RSI

Relative Strength Index

IND_RVI

Relative Vigor Index

IND_SAR

Parabolic SAR

IND_STDDEV

Standard Deviation

IND_STOCHASTIC

Stochastic Oscillator

IND_TEMA

Triple Exponential Moving Average

IND_TRIX

Triple Exponential Moving Averages Oscillator

IND_VIDYA

Variable Index Dynamic Average

IND_VOLUMES

Volumes

IND_WPR

Williams' Percent Range

2000-2016, MetaQuotes Software Corp.

640

Standard Constants, Enumerations and Structures

Data Type Identifiers


When creating an indicator handle using the IndicatorCreate() function, an array of MqlParam type
must be specified as the last parameter. Accordingly, the MqlParam structure, describing indicator,
contains a special field type. This field contains information about the data type (real, integer or
string type) that are passed by a particular element of the array. The value of this field of the
MqlParam structure may be one of ENUM_DATATYPE values.
ENUM_DATATYPE
Identifier

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.

2000-2016, MetaQuotes Software Corp.

641

Standard Constants, Enumerations and Structures

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.

2000-2016, MetaQuotes Software Corp.

642

Standard Constants, Enumerations and Structures

Client Terminal Properties


Information about the client terminal can be obtained by two functions: TerminalInfoInteger() and
TerminalInfoString().
For
parameters,
these
functions
accept
values
from
ENUM_TERMINAL_INFO_INTEGER and ENUM_TERMINAL_INFO_STRING respectively.
ENUM_TERMINAL_INFO_INTEGER
Identifier

Description

Type

TERMINAL_BUILD

The client
number

terminal

build

TERMINAL_COMMUNITY_ACCO
UNT

The flag indicates the presence


of
MQL5.community
authorization data in the
terminal

bool

TERMINAL_COMMUNITY_CONNE
CTION

Connection
MQL5.community

bool

TERMINAL_CONNECTED

Connection to a trade server

bool

TERMINAL_DLLS_ALLOWED

Permission to use DLL

bool

TERMINAL_TRADE_ALLOWED

Permission to trade

bool

TERMINAL_EMAIL_ENABLED

Permission to send e-mails


using SMTP-server and login,
specified in the terminal
settings

bool

TERMINAL_FTP_ENABLED

Permission to send reports


using FTP-server and login,
specified in the terminal
settings

bool

TERMINAL_NOTIFICATIONS_EN
ABLED

Permission
to
send
notifications to smartphone

bool

TERMINAL_MAXBARS

The maximal bars count on the


chart

int

TERMINAL_MQID

The flag indicates the presence


of MetaQuotes ID data for Push
notifications

bool

TERMINAL_CODEPAGE

Number of the code page of the


language installed in the client
terminal

int

TERMINAL_CPU_CORES

The number of CPU cores in the


system

int

TERMINAL_DISK_SPACE

Free disk space for the MQL5


\Files folder of the terminal
(agent), MB

int

to

2000-2016, MetaQuotes Software Corp.

int

643

Standard Constants, Enumerations and Structures


TERMINAL_MEMORY_PHYSICAL

Physical memory in the system,


MB

int

TERMINAL_MEMORY_TOTAL

Memory available
process
of
the
(agent), MB

to the
terminal

int

TERMINAL_MEMORY_AVAILABL
E

Free memory of the terminal


(agent) process, MB

int

TERMINAL_MEMORY_USED

Memory used by the terminal


(agent), MB

int

TERMINAL_X64

Indication
terminal"

bool

TERMINAL_OPENCL_SUPPORT

The version of the supported


OpenCL in the format of
0x00010002 = 1.2. "0" means
that OpenCL is not supported

int

TERMINAL_SCREEN_DPI

The resolution of information


display on the screen is
measured as number of Dots in
a line per Inch (DPI).
Knowing the parameter value,
you can set the size of
graphical objects so that they
look the same on monitors with
different
resolution
characteristics.

int

TERMINAL_PING_LAST

The last known value of a ping


to
a
trade
server
in
microseconds. One second
comprises of one million
microseconds

int

of

the

"64-bit

Example of scaling factor calculation:


//--- Creating a 1.5 inch wide button on a screen
int screen_dpi = TerminalInfoInteger(TERMINAL_SCREEN_DPI); // Find DPI of the user monitor
int base_width = 144;

// The basic width in the screen points

int width

// Calculate the button width for the us

= (button_width * screen_dpi) / 96;

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

2000-2016, MetaQuotes Software Corp.

644

Standard Constants, Enumerations and Structures

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

Language of the terminal

string

TERMINAL_COMPANY

Company name

string

TERMINAL_NAME

Terminal name

string

TERMINAL_PATH

Folder from which the terminal


is started

string

TERMINAL_DATA_PATH

Folder in which terminal data


are stored

string

TERMINAL_COMMONDATA_PAT
H

Common path for all of the


terminals
installed on
a
computer

string

For a better understanding of paths, stored in properties of TERMINAL_PATH, TERMINAL_DATA_PATH


and TERMINAL_COMMONDATA_PATH parameters, it is recommended to execute the script, which will
return these values for the current copy of the client terminal, installed on your computer
Example: Script returns information about the client terminal paths
//+------------------------------------------------------------------+
//|

Check_TerminalPaths.mq5 |

//|

Copyright 2009, MetaQuotes Software Corp. |

//|

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()
{
//---

2000-2016, MetaQuotes Software Corp.

645

Standard Constants, Enumerations and Structures


Print("TERMINAL_PATH = ",TerminalInfoString(TERMINAL_PATH));
Print("TERMINAL_DATA_PATH = ",TerminalInfoString(TERMINAL_DATA_PATH));
Print("TERMINAL_COMMONDATA_PATH = ",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
}

As result of the script execution in the Experts Journal you will see a messages, like the following:

2000-2016, MetaQuotes Software Corp.

646

Standard Constants, Enumerations and Structures

Running MQL5 Program Properties


To obtain information about the currently running mql5
ENUM_MQL_INFO_INTEGER and ENUM_MQL_INFO_STRING are used.

program,

constants

For function MQLInfoInteger


ENUM_MQL_INFO_INTEGER
Identifier

Description

Type

MQL_MEMORY_LIMIT

Maximum possible amount of


dynamic memory for MQL5
program in MB

int

MQL_MEMORY_USED

The memory size used by MQL5


program in MB

int

MQL_PROGRAM_TYPE

Type of the mql5 program

ENUM_PROGRAM_TYPE

MQL_DLLS_ALLOWED

The permission to use DLL for


the given executed program

bool

MQL_TRADE_ALLOWED

The permission to trade for


the given executed program

bool

MQL_SIGNALS_ALLOWED

The permission to modify the


Signals for the given executed
program

bool

MQL_DEBUG

The flag, that indicates the


debug mode

bool

MQL_PROFILER

The flag, that indicates the


program operating in the code
profiling mode

bool

MQL_TESTER

The flag, that indicates the


tester process

bool

MQL_OPTIMIZATION

The flag, that indicates the


optimization process

bool

MQL_VISUAL_MODE

The flag, that indicates the


visual tester process

bool

MQL_FRAME_MODE

The flag, that indicates the


Expert Advisor operating in
gathering optimization result
frames mode

bool

MQL_LICENSE_TYPE

Type of license of the EX5


module. The license refers to
the EX5 module, from which a
request
is
made
using
MQLInfoInteger(MQL_LICENSE_
TYPE).

ENUM_LICENSE_TYPE

2000-2016, MetaQuotes Software Corp.

from

647

Standard Constants, Enumerations and Structures


For function MQLInfoString
ENUM_MQL_INFO_STRING
Identifier

Description

Type

MQL_PROGRAM_NAME

Name of the
executed

mql5-program

string

MQL5_PROGRAM_PATH

Path for the given executed


program

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

A free unlimited version

LICENSE_DEMO

A trial version of a paid product from the


Market. It works only in the strategy tester

LICENSE_FULL

A purchased licensed version allows at least 5


activations. The number of activations is
specified by seller. Seller may increase the
allowed number of activations

LICENSE_TIME

A version with a limited term license

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:
{

2000-2016, MetaQuotes Software Corp.

648

Standard Constants, Enumerations and Structures


Print(__FILE__+" is Expert Advisor");
break;
}
case PROGRAM_INDICATOR:
{
Print(__FILE__+" is custom indicator");
break;
}
default:Print("MQL5 program type value is ",mql_program);
}

2000-2016, MetaQuotes Software Corp.

649

Standard Constants, Enumerations and Structures

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

Symbol is selected in Market


Watch

bool

SYMBOL_SESSION_DEALS

Number of deals in the current


session

long

SYMBOL_SESSION_BUY_ORDERS

Number of Buy orders at the


moment

long

SYMBOL_SESSION_SELL_ORDER
S

Number of Sell orders at the


moment

long

SYMBOL_VOLUME

Volume of the last deal

long

SYMBOL_VOLUMEHIGH

Maximal day volume

long

SYMBOL_VOLUMELOW

Minimal day volume

long

SYMBOL_TIME

Time of the last quote

datetime

SYMBOL_DIGITS

Digits after a decimal point

int

SYMBOL_SPREAD_FLOAT

Indication of a floating spread

bool

SYMBOL_SPREAD

Spread value in points

int

SYMBOL_TICKS_BOOKDEPTH

Maximal number of requests


shown in Depth of Market. For
symbols that have no queue of
requests, the value is equal to
zero.

int

SYMBOL_TRADE_CALC_MODE

Contract price calculation mode

ENUM_SYMBOL_CALC_MODE

SYMBOL_TRADE_MODE

Order execution type

ENUM_SYMBOL_TRADE_MODE

SYMBOL_START_TIME

Date of the symbol trade


beginning (usually used for
futures)

datetime

SYMBOL_EXPIRATION_TIME

Date of the symbol trade end


(usually used for futures)

datetime

SYMBOL_TRADE_STOPS_LEVEL

Minimal indention in points


from the current close price to
place Stop orders

int

2000-2016, MetaQuotes Software Corp.

650

Standard Constants, Enumerations and Structures


SYMBOL_TRADE_FREEZE_LEVEL

Distance to freeze
operations in points

trade

int

SYMBOL_TRADE_EXEMODE

Deal execution mode

ENUM_SYMBOL_TRADE_EXECUT
ION

SYMBOL_SWAP_MODE

Swap calculation model

ENUM_SYMBOL_SWAP_MODE

SYMBOL_SWAP_ROLLOVER3DA
YS

Day of week to charge 3 days


swap rollover

ENUM_DAY_OF_WEEK

SYMBOL_EXPIRATION_MODE

Flags
of
allowed
expiration modes

order

int

SYMBOL_FILLING_MODE

Flags of allowed order filling


modes

int

SYMBOL_ORDER_MODE

Flags of allowed order types

int

SYMBOL_OPTION_MODE

Option type

ENUM_SYMBOL_OPTION_MODE

SYMBOL_OPTION_RIGHT

Option right (Call/Put)

ENUM_SYMBOL_OPTION_RIGH
T

For function SymbolInfoDouble()


ENUM_SYMBOL_INFO_DOUBLE
Identifier

Description

Type

SYMBOL_BID

Bid - best sell offer

double

SYMBOL_BIDHIGH

Maximal Bid of the day

double

SYMBOL_BIDLOW

Minimal Bid of the day

double

SYMBOL_ASK

Ask - best buy offer

double

SYMBOL_ASKHIGH

Maximal Ask of the day

double

SYMBOL_ASKLOW

Minimal Ask of the day

double

SYMBOL_LAST

Price of the last deal

double

SYMBOL_LASTHIGH

Maximal Last of the day

double

SYMBOL_LASTLOW

Minimal Last of the day

double

SYMBOL_OPTION_STRIKE

The strike price of an option.


The price at which an option
buyer can buy (in a Call option)
or sell (in a Put option) the
underlying asset, and the option
seller is obliged to sell or buy the
appropriate amount of the
underlying asset.

double

SYMBOL_POINT

Symbol point value

double

SYMBOL_TRADE_TICK_VALUE

Value

of

2000-2016, MetaQuotes Software Corp.

double

651

Standard Constants, Enumerations and Structures


SYMBOL_TRADE_TICK_VALUE_PR
OFIT
SYMBOL_TRADE_TICK_VALUE_
PROFIT

Calculated tick price


profitable position

for

double

SYMBOL_TRADE_TICK_VALUE_
LOSS

Calculated tick price for a losing


position

double

SYMBOL_TRADE_TICK_SIZE

Minimal price change

double

SYMBOL_TRADE_CONTRACT_S
IZE

Trade contract size

double

SYMBOL_VOLUME_MIN

Minimal volume for a deal

double

SYMBOL_VOLUME_MAX

Maximal volume for a deal

double

SYMBOL_VOLUME_STEP

Minimal volume change step for


deal execution

double

SYMBOL_VOLUME_LIMIT

Maximum allowed aggregate


volume of an open position and
pending orders in one direction
(buy or sell) for the symbol. For
example, with the limitation of 5
lots, you can have an open buy
position with the volume of 5
lots and place a pending order
Sell Limit with the volume of 5
lots. But in this case you cannot
place a Buy Limit pending order
(since the total volume in one
direction
will exceed
the
limitation) or place Sell Limit
with the volume more than 5
lots.

double

SYMBOL_SWAP_LONG

Long swap value

double

SYMBOL_SWAP_SHORT

Short swap value

double

SYMBOL_MARGIN_INITIAL

Initial margin means the amount


in the margin currency required
for opening a position with the
volume of one lot. It is used for
checking a client's assets when
he or she enters the market.

double

SYMBOL_MARGIN_MAINTENAN
CE

The maintenance margin. If it is


set, it sets the margin amount in
the margin currency of the
symbol, charged from one lot. It
is used for checking a client's
assets when his/her account
state
changes.
If
the

double

2000-2016, MetaQuotes Software Corp.

652

Standard Constants, Enumerations and Structures


maintenance margin is equal to
0, the initial margin is used.
SYMBOL_SESSION_VOLUME

Summary volume
session deals

current

double

SYMBOL_SESSION_TURNOVER

Summary turnover of the current


session

double

SYMBOL_SESSION_INTEREST

Summary open interest

double

SYMBOL_SESSION_BUY_ORDER
S_VOLUME

Current volume of Buy orders

double

SYMBOL_SESSION_SELL_ORDE
RS_VOLUME

Current volume of Sell orders

double

SYMBOL_SESSION_OPEN

Open price of the current session

double

SYMBOL_SESSION_CLOSE

Close price
session

current

double

SYMBOL_SESSION_AW

Average weighted price of the


current session

double

SYMBOL_SESSION_PRICE_SETT
LEMENT

Settlement price of the current


session

double

SYMBOL_SESSION_PRICE_LIMI
T_MIN

Minimal price of the current


session

double

SYMBOL_SESSION_PRICE_LIMI
T_MAX

Maximal price of the current


session

double

SYMBOL_MARGIN_HEDGED

Contract size or margin value


per one lot of hedged positions
(oppositely directed positions of
one symbol). Two
margin
calculation methods are possible
for hedged positions. The
calculation method is defined by
the broker.

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

2000-2016, MetaQuotes Software Corp.

653

Standard Constants, Enumerations and Structures


appropriate
formula
in
accordance with the type of
the
financial
instrument
(SYMBOL_TRADE_CALC_MODE)
.
Calculation for the largest
position:
The SYMBOL_MARGIN_HEDGED
value is not taken into
account.
The volume of all short and all
long positions of a symbol is
calculated.
For each direction, a weighted
average open price and a
weighted average rate of
conversion to the deposit
currency is calculated.
Next, using the appropriate
formula chosen in accordance
with
the
symbol
type
(SYMBOL_TRADE_CALC_MODE)
the margin is calculate for the
shot and the long part.
The largest one of the values
is used as the margin.
For function SymbolInfoString()
ENUM_SYMBOL_INFO_STRING
Identifier

Description

Type

SYMBOL_BASIS

The underlying asset


derivative

of

SYMBOL_CURRENCY_BASE

Basic currency of a symbol

string

SYMBOL_CURRENCY_PROFIT

Profit currency

string

SYMBOL_CURRENCY_MARGIN

Margin currency

string

SYMBOL_BANK

Feeder of the current quote

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

2000-2016, MetaQuotes Software Corp.

string

654

Standard Constants, Enumerations and Structures


uniquely identifies a security.
The presence of this symbol
property is determined on the
side of a trade server.
SYMBOL_PATH

Path in the symbol tree

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

The order is valid during the


unlimited time period, until it
is explicitly canceled

SYMBOL_EXPIRATION_DAY

The order is valid till the end of


the 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

2000-2016, MetaQuotes Software Corp.

Description

655

Standard Constants, Enumerations and Structures


Fill or Kill

SYMBOL_FILLING_FOK

This policy means that


a deal can be executed
only with the specified
volume.
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.

Immediate or Cancel

SYMBOL_FILLING_IOC

In this case a trader


agrees to execute a
deal with the volume
maximally available in
the market within that
indicated in the order.
In case the order
cannot
be
filled
completely,
the
available volume of
the order will be filled,
and the remaining
volume
will
be
canceled.
The
possibility of using IOC
orders is determined
at the trade server.

Return

No identifier

This policy is used only


for market orders (Buy
and Sell), limit and
stop limit orders and
only for the symbols
with
Market
or
Exchange execution. In
case of partial filling a
market or limit order
with remaining volume
is not canceled but
processed further.

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

2000-2016, MetaQuotes Software Corp.

656

Standard Constants, Enumerations and Structures


types. To find out whether the other policies are allowed, use the SYMBOL_FILLING_FOK and
SYMBOL_FILLING_IOC properties.
Example:
//+------------------------------------------------------------------+
//| Checks if the specified filling mode is allowed

//+------------------------------------------------------------------+
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

Market orders are allowed (Buy


and Sell)

SYMBOL_ORDER_LIMIT

Limit orders are allowed (Buy


Limit and Sell Limit)

SYMBOL_ORDER_STOP

Stop orders are allowed (Buy


Stop and Sell Stop)

SYMBOL_ORDER_STOP_LIMIT

Stop-limit orders are allowed


(Buy Stop Limit and Sell Stop
Limit)

SYMBOL_ORDER_SL

16

Stop Loss is allowed

SYMBOL_ORDER_TP

32

Take Profit is allowed

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

2000-2016, MetaQuotes Software Corp.

657

Standard Constants, Enumerations and Structures


if((SYMBOL_ORDER_LIMIT&symbol_order_mode)==SYMBOL_ORDER_LIMIT)
Print(symbol+": Buy Limit and Sell Limit orders are allowed");
//--- check for Stop orders
if((SYMBOL_ORDER_STOP&symbol_order_mode)==SYMBOL_ORDER_STOP)
Print(symbol+": Buy Stop and Sell Stop orders are allowed");
//--- check for Stop Limit orders
if((SYMBOL_ORDER_STOP_LIMIT&symbol_order_mode)==SYMBOL_ORDER_STOP_LIMIT)
Print(symbol+": Buy Stop Limit and Sell Stop Limit orders are allowed");
//--- check if placing a Stop Loss orders is allowed
if((SYMBOL_ORDER_SL&symbol_order_mode)==SYMBOL_ORDER_SL)
Print(symbol+": Stop Loss orders are allowed");
//--- check if placing a Take Profit orders is allowed
if((SYMBOL_ORDER_TP&symbol_order_mode)==SYMBOL_ORDER_TP)
Print(symbol+": Take Profit orders are allowed");
//--}

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

Forex mode - calculation of profit


and margin for Forex

Margin: Lots*Contract_Size/
Leverage
Profit:
(close_priceopen_price)
*Contract_Size*Lots

SYMBOL_CALC_MODE_FUTUR
ES

Futures mode - calculation of


margin and profit for futures

Margin:
Lots
*InitialMargin*Percentage/100
Profit:
(close_priceopen_price)*TickPrice/
TickSize*Lots

SYMBOL_CALC_MODE_CFD

CFD mode - calculation of margin


and profit for CFD

Margin:
Lots
*ContractSize*MarketPrice*Per
centage/100
Profit:
(close_priceopen_price)
*Contract_Size*Lots

SYMBOL_CALC_MODE_CFDIND
EX

CFD index mode - calculation of


margin and profit for CFD by
indexes

Margin:
(Lots*ContractSize*MarketPric
e)*TickPrice/TickSize
Profit:
(close_priceopen_price)
*Contract_Size*Lots

SYMBOL_CALC_MODE_CFDLEV

CFD Leverage mode - calculation

Margin:

2000-2016, MetaQuotes Software Corp.

658

Standard Constants, Enumerations and Structures


ERAGE

of margin and profit for CFD at


leverage trading

(Lots*ContractSize*MarketPric
e*Percentage)/Leverage
Profit:
(close_priceopen_price)
*Contract_Size*Lots

SYMBOL_CALC_MODE_EXCH_
STOCKS

Exchange mode calculation of


margin and profit for trading
securities on a stock exchange

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

FORTS Futures mode calculation


of margin and profit for trading
futures contracts on FORTS. The
margin may be reduced by the
amount
of
MarginDiscount
deviation according
to
the
following rules:
1. If the price of a long position
(buy order) is less than the
estimated price, MarginDiscount =
Lots*((PriceSettle-PriceOrder)
*TickPrice/TickSize)
2. If the price of a short position
(sell order) exceeds the estimated
price,
MarginDiscount
=
Lots*((PriceOrder-PriceSettle)
*TickPrice/TickSize)
where:
o PriceSettle

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

Collateral mode - a symbol is used


as a non-tradable asset on a
trading account. The market value
of an open position is calculated

Margin: no
Profit: no
Market Value:
Lots*ContractSize*MarketPric

2000-2016, MetaQuotes Software Corp.

659

Standard Constants, Enumerations and Structures


based on the volume, current
market price, contract size and
liquidity ratio. The value is
included into Assets, which are
added to Equity. Open positions of
such symbols increase the Free
Margin amount and are used as
additional margin (collateral) for
open positions
of
tradable
instruments.

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

Trade is disabled for the symbol

SYMBOL_TRADE_MODE_LONGONLY

Allowed only long positions

SYMBOL_TRADE_MODE_SHORTONLY

Allowed only short positions

SYMBOL_TRADE_MODE_CLOSEONLY

Allowed only position close operations

SYMBOL_TRADE_MODE_FULL

No trade restrictions

Possible deal execution modes


ENUM_SYMBOL_TRADE_EXECUTION.

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

Methods of swap calculation at position transfer are specified in enumeration


ENUM_SYMBOL_SWAP_MODE. The method of swap calculation determines the units of measure of the
SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT parameters. For example, if swaps are charged in
the client deposit currency, then the values of those parameters are specified as an amount of money
in the client deposit currency.
ENUM_SYMBOL_SWAP_MODE

2000-2016, MetaQuotes Software Corp.

660

Standard Constants, Enumerations and Structures


Identifier

Description

SYMBOL_SWAP_MODE_DISABLED

Swaps disabled (no swaps)

SYMBOL_SWAP_MODE_POINTS

Swaps are charged in points

SYMBOL_SWAP_MODE_CURRENCY_SYMBOL

Swaps are charged in money in base currency of


the symbol

SYMBOL_SWAP_MODE_CURRENCY_MARGIN

Swaps are charged in money in margin currency


of the symbol

SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT

Swaps are charged in money, in client deposit


currency

SYMBOL_SWAP_MODE_INTEREST_CURRENT

Swaps are charged as the specified annual


interest from the instrument price at calculation
of swap (standard bank year is 360 days)

SYMBOL_SWAP_MODE_INTEREST_OPEN

Swaps are charged as the specified annual


interest from the open price of position
(standard bank year is 360 days)

SYMBOL_SWAP_MODE_REOPEN_CURRENT

Swaps are charged by reopening positions. At


the end of a trading day the position is closed.
Next day it is reopened by the close price +/specified number of points (parameters
SYMBOL_SWAP_LONG
and
SYMBOL_SWAP_SHORT)

SYMBOL_SWAP_MODE_REOPEN_BID

Swaps are charged by reopening positions. At


the end of a trading day the position is closed.
Next day it is reopened by the current Bid price
+/- specified number of points (parameters
SYMBOL_SWAP_LONG
and
SYMBOL_SWAP_SHORT)

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

2000-2016, MetaQuotes Software Corp.

661

Standard Constants, Enumerations and Structures

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

A call option gives you the right to buy an asset


at a specified price

SYMBOL_OPTION_RIGHT_PUT

A put option gives you the right to sell an asset


at a specified price

ENUM_SYMBOL_OPTION_MODE
Identifier

Description

SYMBOL_OPTION_MODE_EUROPEAN

European option may only be exercised on a


specified date (expiration, execution date,
delivery date)

SYMBOL_OPTION_MODE_AMERICAN

American option may be exercised on any


trading day on or before expiry. The period
within which a buyer can exercise the option is
specified for it

2000-2016, MetaQuotes Software Corp.

662

Standard Constants, Enumerations and Structures

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

Account trade mode

ENUM_ACCOUNT_TRADE_MODE

ACCOUNT_LEVERAGE

Account leverage

long

ACCOUNT_LIMIT_ORDERS

Maximum allowed number of


active pending orders

int

ACCOUNT_MARGIN_SO_MODE

Mode for setting the minimal


allowed margin

ENUM_ACCOUNT_STOPOUT_MO
DE

ACCOUNT_TRADE_ALLOWED

Allowed trade for the current


account

bool

ACCOUNT_TRADE_EXPERT

Allowed trade for an Expert


Advisor

bool

ACCOUNT_MARGIN_MODE

Margin calculation mode

ENUM_ACCOUNT_MARGIN_MOD
E

For the function AccountInfoDouble()


ENUM_ACCOUNT_INFO_DOUBLE
Identifier

Description

Type

ACCOUNT_BALANCE

Account balance in the deposit


currency

double

ACCOUNT_CREDIT

Account credit in the deposit


currency

double

ACCOUNT_PROFIT

Current profit of an account in


the deposit currency

double

ACCOUNT_EQUITY

Account equity in the deposit


currency

double

ACCOUNT_MARGIN

Account margin used in the


deposit currency

double

ACCOUNT_MARGIN_FREE

Free margin of an account in


the deposit currency

double

ACCOUNT_MARGIN_LEVEL

Account

double

margin

level

in

2000-2016, MetaQuotes Software Corp.

663

Standard Constants, Enumerations and Structures


percents
ACCOUNT_MARGIN_SO_CALL

Margin call level. Depending on


the
set
ACCOUNT_MARGIN_SO_MODE
is expressed in percents or in
the deposit currency

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

Initial margin. The amount


reserved on an account to
cover the margin of all pending
orders

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

The current liabilities on an


account

double

ACCOUNT_COMMISSION_BLOCK
ED

The
current
commission amount
account

double

assets

of

blocked
on an

For function AccountInfoString()


ENUM_ACCOUNT_INFO_STRING
Identifier

Description

Type

ACCOUNT_NAME

Client name

string

ACCOUNT_SERVER

Trade server name

string

ACCOUNT_CURRENCY

Account currency

string

ACCOUNT_COMPANY

Name of a company that serves


the account

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

2000-2016, MetaQuotes Software Corp.

664

Standard Constants, Enumerations and Structures


ACCOUNT_TRADE_MODE_DEMO

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 stop out mode in percents

ACCOUNT_STOPOUT_MODE_MONEY

Account stop out mode in money

ENUM_ACCOUNT_MARGIN_MODE
Identifier

Description

ACCOUNT_MARGIN_MODE_RETAIL_NETTING

Used for the OTC markets to interpret positions


in the "netting" mode (only one position can
exist for one symbol). The margin is calculated
based
on
the
symbol
type
(SYMBOL_TRADE_CALC_MODE).

ACCOUNT_MARGIN_MODE_EXCHANGE

Used for the exchange markets. Margin is


calculated based on the discounts specified in
symbol settings. Discounts are set by the
broker, but not less than the values set by the
exchange.

ACCOUNT_MARGIN_MODE_RETAIL_HEDGING

Used for the exchange markets where individual


positions are possible (hedging, multiple
positions can exist for one symbol). The margin
is calculated based on the symbol type
(SYMBOL_TRADE_CALC_MODE)
taking
into
account
the
hedged
margin
(SYMBOL_MARGIN_HEDGED).

An example of the script that outputs a brief account information.


//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
//--- Name of the company
string company=AccountInfoString(ACCOUNT_COMPANY);
//--- Name of the client
string name=AccountInfoString(ACCOUNT_NAME);

2000-2016, MetaQuotes Software Corp.

665

Standard Constants, Enumerations and Structures


//--- Account number
long login=AccountInfoInteger(ACCOUNT_LOGIN);
//--- Name of the server
string server=AccountInfoString(ACCOUNT_SERVER);
//--- Account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
//--- Demo, contest or real account

ENUM_ACCOUNT_TRADE_MODE account_type=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_M
//--- Now transform the value of

the enumeration into an understandable form

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

2000-2016, MetaQuotes Software Corp.

666

Standard Constants, Enumerations and Structures

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

The value of the initial deposit

double

STAT_WITHDRAWAL

Money withdrawn
account

an

double

STAT_PROFIT

Net profit after testing, the


sum of STAT_GROSS_PROFIT
and
STAT_GROSS_LOSS
(STAT_GROSS_LOSS is always
less than or equal to zero)

double

STAT_GROSS_PROFIT

Total profit, the sum of all


profitable (positive) trades.
The value is greater than or
equal to zero

double

STAT_GROSS_LOSS

Total loss, the sum of all


negative trades. The value is
less than or equal to zero

double

STAT_MAX_PROFITTRADE

Maximum profit the largest


value of all profitable trades.
The value is greater than or
equal to zero

double

STAT_MAX_LOSSTRADE

Maximum loss the lowest


value of all losing trades. The
value is less than or equal to
zero

double

STAT_CONPROFITMAX

Maximum profit in a series of


profitable trades. The value is
greater than or equal to zero

double

STAT_CONPROFITMAX_TRADES

The number of trades that


have
formed
STAT_CONPROFITMAX
(maximum profit in a series of
profitable trades)

int

STAT_MAX_CONWINS

The total profit of the longest

double

from

2000-2016, MetaQuotes Software Corp.

667

Standard Constants, Enumerations and Structures


series of profitable trades
STAT_MAX_CONPROFIT_TRADE
S

The number of trades in the


longest series of profitable
trades STAT_MAX_CONWINS

int

STAT_CONLOSSMAX

Maximum loss in a series of


losing trades. The value is less
than or equal to zero

double

STAT_CONLOSSMAX_TRADES

The number of trades that


have
formed
STAT_CONLOSSMAX (maximum
loss in a series of losing
trades)

int

STAT_MAX_CONLOSSES

The total loss of the longest


series of losing trades

double

STAT_MAX_CONLOSS_TRADES

The number of trades in the


longest series of losing trades
STAT_MAX_CONLOSSES

int

STAT_BALANCEMIN

Minimum balance value

double

STAT_BALANCE_DD

Maximum balance drawdown in


monetary terms. In the process
of trading, a balance may have
numerous drawdowns; here the
largest value is taken

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

Maximum balance drawdown as


a percentage. In the process of
trading, a balance may have
numerous drawdowns, for each
of which the relative drawdown
value in percents is calculated.
The greatest value is returned

double

STAT_BALANCE_DD_RELATIVE

Balance drawdown in monetary


terms that was recorded at the
moment of the maximum
balance
drawdown
as
a
percentage
(STAT_BALANCE_DDREL_PERCE
NT).

double

STAT_EQUITYMIN

Minimum equity value

double

2000-2016, MetaQuotes Software Corp.

668

Standard Constants, Enumerations and Structures


STAT_EQUITY_DD

Maximum equity drawdown in


monetary terms. In the process
of
trading,
numerous
drawdowns may appear on the
equity; here the largest value
is taken

double

STAT_EQUITYDD_PERCENT

Drawdown in percent that was


recorded at the moment of the
maximum equity drawdown in
monetary
terms
(STAT_EQUITY_DD).

double

STAT_EQUITY_DDREL_PERCENT

Maximum equity drawdown as


a percentage. In the process of
trading, an equity may have
numerous drawdowns, for each
of which the relative drawdown
value in percents is calculated.
The greatest value is returned

double

STAT_EQUITY_DD_RELATIVE

Equity drawdown in monetary


terms that was recorded at the
moment of the maximum
equity drawdown in percent
(STAT_EQUITY_DDREL_PERCEN
T).

double

STAT_EXPECTED_PAYOFF

Expected payoff

double

STAT_PROFIT_FACTOR

Profit factor, equal to


the
ratio of STAT_GROSS_PROFIT/
STAT_GROSS_LOSS.
If
STAT_GROSS_LOSS=0,
the
profit factor is equal to
DBL_MAX

double

STAT_RECOVERY_FACTOR

Recovery factor, equal to the


ratio
of
STAT_PROFIT/
STAT_BALANCE_DD

double

STAT_SHARPE_RATIO

Sharpe ratio

double

STAT_MIN_MARGINLEVEL

Minimum value of the margin


level

double

STAT_CUSTOM_ONTESTER

The value of the calculated


custom optimization criterion
returned by the OnTester()
function

double

STAT_DEALS

The number of deals

int

STAT_TRADES

The number of trades

int

STAT_PROFIT_TRADES

Profitable trades

int

2000-2016, MetaQuotes Software Corp.

669

Standard Constants, Enumerations and Structures


STAT_LOSS_TRADES

Losing trades

int

STAT_SHORT_TRADES

Short trades

int

STAT_LONG_TRADES

Long trades

int

STAT_PROFIT_SHORTTRADES

Profitable short trades

int

STAT_PROFIT_LONGTRADES

Profitable long trades

int

STAT_PROFITTRADES_AVGCON

Average length of a profitable


series of trades

int

STAT_LOSSTRADES_AVGCON

Average length of a losing


series of trades

int

2000-2016, MetaQuotes Software Corp.

670

Standard Constants, Enumerations and Structures

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.

2000-2016, MetaQuotes Software Corp.

671

Standard Constants, Enumerations and Structures

History Database Properties


When accessing timeseries the SeriesInfoInteger() function is used for obtaining additional symbol
information. Identifier of a required property is passed as the function parameter. The identifier can
be one of values of ENUM_SERIES_INFO_INTEGER.
ENUM_SERIES_INFO_INTEGER
Identifier

Description

Type

SERIES_BARS_COUNT

Bars count for the symbolperiod for the current moment

long

SERIES_FIRSTDATE

The very first date for the


symbol-period for the current
moment

datetime

SERIES_LASTBAR_DATE

Open time of the last bar of


the symbol-period

datetime

SERIES_SERVER_FIRSTDATE

The very first date in the


history of the symbol on the
server regardless of
the
timeframe

datetime

SERIES_TERMINAL_FIRSTDATE

The very first date in the


history of the symbol in the
client terminal, regardless of
the timeframe

datetime

SERIES_SYNCHRONIZED

Symbol/period
data
synchronization flag for the
current moment

bool

2000-2016, MetaQuotes Software Corp.

672

Standard Constants, Enumerations and Structures

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

Order setup time

datetime

ORDER_TYPE

Order type

ENUM_ORDER_TYPE

ORDER_STATE

Order state

ENUM_ORDER_STATE

ORDER_TIME_EXPIRATION

Order expiration time

datetime

ORDER_TIME_DONE

Order execution or cancellation


time

datetime

ORDER_TIME_SETUP_MSC

The time of placing an order


for execution in milliseconds
since 01.01.1970

long

ORDER_TIME_DONE_MSC

Order execution/cancellation
time in milliseconds since
01.01.1970

long

ORDER_TYPE_FILLING

Order filling type

ENUM_ORDER_TYPE_FILLING

ORDER_TYPE_TIME

Order lifetime

ENUM_ORDER_TYPE_TIME

ORDER_MAGIC

ID of an Expert Advisor that


has placed the order (designed
to ensure that each Expert
Advisor places its own unique
number)

long

ORDER_POSITION_ID

Position identifier that is set to


an order as soon as it is
executed. Each executed order
results in a deal that opens or
modifies an already existing
position. The identifier of
exactly this position is set to
the executed order at this
moment.

long

ORDER_POSITION_BY_ID

Identifier of an opposite
position used for closing by
order ORDER_TYPE_CLOSE_BY

long

For functions OrderGetDouble() and HistoryOrderGetDouble()

2000-2016, MetaQuotes Software Corp.

673

Standard Constants, Enumerations and Structures


ENUM_ORDER_PROPERTY_DOUBLE
Identifier

Description

Type

ORDER_VOLUME_INITIAL

Order initial volume

double

ORDER_VOLUME_CURRENT

Order current volume

double

ORDER_PRICE_OPEN

Price specified in the order

double

ORDER_SL

Stop Loss value

double

ORDER_TP

Take Profit value

double

ORDER_PRICE_CURRENT

The current price of the order


symbol

double

ORDER_PRICE_STOPLIMIT

The Limit order price for the


StopLimit order

double

For functions OrderGetString() and HistoryOrderGetString()


ENUM_ORDER_PROPERTY_STRING
Identifier

Description

Type

ORDER_SYMBOL

Symbol of the order

string

ORDER_COMMENT

Order comment

string

ORDER_EXTERNAL_ID

Order identifier in an external


trading
system
(on
the
Exchange)

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

Market Buy order

ORDER_TYPE_SELL

Market Sell order

ORDER_TYPE_BUY_LIMIT

Buy Limit pending order

ORDER_TYPE_SELL_LIMIT

Sell Limit pending order

ORDER_TYPE_BUY_STOP

Buy Stop pending order

ORDER_TYPE_SELL_STOP

Sell Stop pending order

ORDER_TYPE_BUY_STOP_LIMIT

Upon reaching the order price, a pending Buy


Limit order is placed at the StopLimit price

2000-2016, MetaQuotes Software Corp.

674

Standard Constants, Enumerations and Structures


ORDER_TYPE_SELL_STOP_LIMIT

Upon reaching the order price, a pending Sell


Limit order is placed at the StopLimit price

ORDER_TYPE_CLOSE_BY

Order to close a position by an opposite one

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 checked, but not yet accepted by broker

ORDER_STATE_PLACED

Order accepted

ORDER_STATE_CANCELED

Order canceled by client

ORDER_STATE_PARTIAL

Order partially executed

ORDER_STATE_FILLED

Order fully executed

ORDER_STATE_REJECTED

Order rejected

ORDER_STATE_EXPIRED

Order expired

ORDER_STATE_REQUEST_ADD

Order is being registered (placing to the trading


system)

ORDER_STATE_REQUEST_MODIFY

Order is being
parameters)

ORDER_STATE_REQUEST_CANCEL

modified

(changing

its

Order is being deleted (deleting from the trading


system)

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.

2000-2016, MetaQuotes Software Corp.

675

Standard Constants, Enumerations and Structures


ORDER_FILLING_IOC

This mode means that a trader agrees to


execute a deal with the volume maximally
available in the market within that indicated in
the order. In case the the entire volume of an
order cannot be filled, the available volume of it
will be filled, and the remaining volume will be
canceled.

ORDER_FILLING_RETURN

This policy is used only for market orders


(ORDER_TYPE_BUY and ORDER_TYPE_SELL),
limit
and
stop
limit
orders
(ORDER_TYPE_BUY_LIMIT,
ORDER_TYPE_SELL_LIMIT,
ORDER_TYPE_BUY_STOP_LIMIT
and
ORDER_TYPE_SELL_STOP_LIMIT ) and only for
the symbols with Market or Exchange execution.
In case of partial filling a market or limit order
with remaining volume is not canceled but
processed further.
For
the
activation
of
the
ORDER_TYPE_BUY_STOP_LIMIT
and
ORDER_TYPE_SELL_STOP_LIMIT
orders,
a
corresponding
limit
order
ORDER_TYPE_BUY_LIMIT/
ORDER_TYPE_SELL_LIMIT
with
the
ORDER_FILLING_RETURN execution type is
created.

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

Good till cancel order

ORDER_TIME_DAY

Good till current trade day order

ORDER_TIME_SPECIFIED

Good till expired order

ORDER_TIME_SPECIFIED_DAY

The order will be effective till 23:59:59 of the


specified day. If this time is outside a trading
session, the order expires in the nearest trading
time.

2000-2016, MetaQuotes Software Corp.

676

Standard Constants, Enumerations and Structures

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

Position open time

datetime

POSITION_TIME_MSC

Position opening time in


milliseconds since 01.01.1970

long

POSITION_TIME_UPDATE

Position changing time


seconds since 01.01.1970

in

long

POSITION_TIME_UPDATE_MSC

Position changing time in


milliseconds since 01.01.1970

long

POSITION_TYPE

Position type

ENUM_POSITION_TYPE

POSITION_MAGIC

Position magic number (see


ORDER_MAGIC)

long

POSITION_IDENTIFIER

The position identifier is a


unique number assigned to
every newly opened position. It
does not change though the
whole position lifetime. As a
rule, it matches the ticket of
the order based on which the
position was opened.

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

Position open price

double

POSITION_SL

Stop Loss

level of

opened

2000-2016, MetaQuotes Software Corp.

double

677

Standard Constants, Enumerations and Structures


position
POSITION_TP

Take Profit level of opened


position

double

POSITION_PRICE_CURRENT

Current price of the position


symbol

double

POSITION_SWAP

Cumulative swap

double

POSITION_PROFIT

Current profit

double

For the function PositionGetString()


ENUM_POSITION_PROPERTY_STRING
Identifier

Description

Type

POSITION_SYMBOL

Symbol of the position

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

2000-2016, MetaQuotes Software Corp.

678

Standard Constants, Enumerations and Structures

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

Deal order number

long

DEAL_TIME

Deal time

datetime

DEAL_TIME_MSC

The time of a deal execution in


milliseconds since 01.01.1970

long

DEAL_TYPE

Deal type

ENUM_DEAL_TYPE

DEAL_ENTRY

Deal entry - entry in, entry out,


reverse

ENUM_DEAL_ENTRY

DEAL_MAGIC

Deal magic number


ORDER_MAGIC)

(see

long

DEAL_POSITION_ID

Identifier of a position, in the


opening,
modification
or
closing of which this deal took
part. Each position has a
unique identifier that is
assigned to all deals executed
for the symbol during the
entire lifetime of the position.

long

For the function HistoryDealGetDouble()


ENUM_DEAL_PROPERTY_DOUBLE
Identifier

Description

Type

DEAL_VOLUME

Deal volume

double

DEAL_PRICE

Deal price

double

DEAL_COMMISSION

Deal commission

double

DEAL_SWAP

Cumulative swap on close

double

DEAL_PROFIT

Deal profit

double

For the function HistoryDealGetString()


ENUM_DEAL_PROPERTY_STRING

2000-2016, MetaQuotes Software Corp.

679

Standard Constants, Enumerations and Structures


Identifier

Description

Type

DEAL_SYMBOL

Deal symbol

string

DEAL_COMMENT

Deal comment

string

DEAL_EXTERNAL_ID

Deal identifier in an external


trading
system
(on
the
Exchange)

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

Daily agent commission

DEAL_TYPE_COMMISSION_AGENT_MONTHLY

Monthly agent commission

DEAL_TYPE_INTEREST

Interest rate

DEAL_TYPE_BUY_CANCELED

Canceled buy deal. There can be a situation


when a previously executed buy deal is canceled.
In this case, the type of the previously executed
deal
(DEAL_TYPE_BUY)
is
changed
to
DEAL_TYPE_BUY_CANCELED, and its profit/loss
is zeroized. Previously obtained profit/loss is
charged/withdrawn using a separated balance
operation

DEAL_TYPE_SELL_CANCELED

Canceled sell deal. There can be a situation


when a previously executed sell deal is canceled.
In this case, the type of the previously executed
deal (DEAL_TYPE_SELL) is
changed
to

2000-2016, MetaQuotes Software Corp.

680

Standard Constants, Enumerations and Structures


DEAL_TYPE_SELL_CANCELED, and its profit/loss
is zeroized. Previously obtained profit/loss is
charged/withdrawn using a separated balance
operation

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

lose a position by an opposite one

2000-2016, MetaQuotes Software Corp.

681

Standard Constants, Enumerations and Structures

Trade Operation Types


Trading is done by sending orders to open positions using the OrderSend() function, as well as to
place, modify or delete pending orders. Each trade order refers to the type of the requested operation.
Trading operations are described in the ENUM_TRADE_REQUEST_ACTIONS enumeration.
ENUM_TRADE_REQUEST_ACTIONS
Identifier

Description

TRADE_ACTION_DEAL

Place a trade order for an immediate execution


with the specified parameters (market order)

TRADE_ACTION_PENDING

Place a trade order for the execution under


specified conditions (pending order)

TRADE_ACTION_SLTP

Modify Stop Loss and Take Profit values of an


opened position

TRADE_ACTION_MODIFY

Modify the parameters of the order placed


previously

TRADE_ACTION_REMOVE

Delete the pending order placed previously

TRADE_ACTION_CLOSE_BY

lose a position by an opposite one

2000-2016, MetaQuotes Software Corp.

682

Standard Constants, Enumerations and Structures

Trade Transaction Types


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

OrderSendAsync functions and its further execution;


Sending a trade request via the terminal graphical interface and its further execution;
Pending orders and stop orders activation on the server;
Performing operations on a trade server side.

The following trade transactions are performed as a result of these actions:


handling a trade request;
changing open orders;
changing orders history;
changing deals history;
changing positions.

For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
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

Adding a new open order.

TRADE_TRANSACTION_ORDER_UPDATE

Updating an open order. The updates include not


only evident changes from the client terminal or
a trade server sides but also changes of an order
state when setting it (for example, transition
from
ORDER_STATE_STARTED
to
ORDER_STATE_PLACED
or
from
ORDER_STATE_PLACED
to
ORDER_STATE_PARTIAL, etc.).

TRADE_TRANSACTION_ORDER_DELETE

Removing an order from the list of the open


ones. An order can be deleted from the open
ones as a result of setting an appropriate
request or execution (filling) and moving to the
history.

2000-2016, MetaQuotes Software Corp.

683

Standard Constants, Enumerations and Structures


TRADE_TRANSACTION_DEAL_ADD

Adding a deal to the history. The action is


performed as a result of an order execution or
performing operations with an account balance.

TRADE_TRANSACTION_DEAL_UPDATE

Updating a deal in the history. There may be


cases when a previously executed deal is
changed on a server. For example, a deal has
been changed in an external trading system
(exchange) where it was previously transferred
by a broker.

TRADE_TRANSACTION_DEAL_DELETE

Deleting a deal from the history. There may be


cases when a previously executed deal is deleted
from a server. For example, a deal has been
deleted in an external trading system
(exchange) where it was previously transferred
by a broker.

TRADE_TRANSACTION_HISTORY_ADD

Adding an order to the history as a result of


execution or cancellation.

TRADE_TRANSACTION_HISTORY_UPDATE

Changing an order located in the orders history.


This type is provided for enhancing functionality
on a trade server side.

TRADE_TRANSACTION_HISTORY_DELETE

Deleting an order from the orders history. This


type is provided for enhancing functionality on a
trade server side.

TRADE_TRANSACTION_POSITION

Changing a position not related to a deal


execution. This type of transaction shows that a
position has been changed on a trade server
side. Position volume, open price, Stop Loss and
Take Profit levels can be changed. Data on
changes are submitted in MqlTradeTransaction
structure via OnTradeTransaction handler.
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

Notification of the fact that a trade request has


been processed by a server and processing result
has been received. Only type field (trade
transaction type) must be analyzed for such
transactions in MqlTradeTransaction structure.
The second and third parameters
of
OnTradeTransaction (request and result) must
be analyzed for additional data.

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

2000-2016, MetaQuotes Software Corp.

684

Standard Constants, Enumerations and Structures


Structure of a Trade Transaction, OnTradeTransaction

2000-2016, MetaQuotes Software Corp.

685

Standard Constants, Enumerations and Structures

Trade Orders in Depth Of Market


For equity securities, the Depth of Market window is available, where you can see the current Buy and
Sell orders. Desired direction of a trade operation, required amount and requested price are specified
for each order.
To obtain information about the current state of the DOM by MQL5 means, the MarketBookGet()
function is used, which places the DOM "screen shot" into the MqlBookInfo array of structures. Each
element of the array in the type field contains information about the direction of the order - the value
of the ENUM_BOOK_TYPE enumeration.
ENUM_BOOK_TYPE
Identifier

Description

BOOK_TYPE_SELL

Sell order (Offer)

BOOK_TYPE_BUY

Buy order (Bid)

BOOK_TYPE_SELL_MARKET

Sell order by Market

BOOK_TYPE_BUY_MARKET

Buy order by Market

See also
Structures and classes, Structure of the DOM, Trade operation types, Market Info

2000-2016, MetaQuotes Software Corp.

686

Standard Constants, Enumerations and Structures

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

Account maximum drawdown

SIGNAL_BASE_PRICE

Signal subscription price

SIGNAL_BASE_ROI

Return on Investment (%)

Enumeration of integer type properties of the trading signal:


ENUM_SIGNAL_BASE_INTEGER
ID

Description

SIGNAL_BASE_DATE_PUBLISHED

Publication date (date when it become available


for subscription)

SIGNAL_BASE_DATE_STARTED

Monitoring starting date

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

Account type (0-real, 1-demo, 2-contest)

Enumeration of string type properties of the trading signal:


ENUM_SIGNAL_BASE_STRING
ID

Description

SIGNAL_BASE_AUTHOR_LOGIN

Author login

SIGNAL_BASE_BROKER

Broker name (company)

SIGNAL_BASE_BROKER_SERVER

Broker server

2000-2016, MetaQuotes Software Corp.

687

Standard Constants, Enumerations and Structures


SIGNAL_BASE_NAME

Signal name

SIGNAL_BASE_CURRENCY

Signal base currency

Enumeration of double type properties of the signal copy settings:


ENUM_SIGNAL_INFO_DOUBLE
ID

Description

SIGNAL_INFO_EQUITY_LIMIT

Equity limit

SIGNAL_INFO_SLIPPAGE

Slippage (used when placing market orders in


synchronization of positions and copying of
trades)

SIGNAL_INFO_VOLUME_PERCENT

Maximum percent of deposit used (%), r/o

Enumeration of integer type properties of the signal copy settings:


ENUM_SIGNAL_INFO_INTEGER
ID

Description

SIGNAL_INFO_CONFIRMATIONS_DISABLED

The flag enables


confirmation dialog

SIGNAL_INFO_COPY_SLTP

Copy Stop Loss and Take Profit flag

SIGNAL_INFO_DEPOSIT_PERCENT

Deposit percent (%)

SIGNAL_INFO_ID

Signal id, r/o

SIGNAL_INFO_SUBSCRIPTION_ENABLED

"Copy trades by subscription" permission flag

SIGNAL_INFO_TERMS_AGREE

"Agree to terms of use of Signals service" flag,


r/o

Enumeration of string type properties of the signal copy settings:


ENUM_SIGNAL_INFO_STRING
ID
SIGNAL_INFO_NAME

Description
Signal name, r/o

See also
Trade signals

2000-2016, MetaQuotes Software Corp.

synchronization

without

688

Standard Constants, Enumerations and Structures

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.

2000-2016, MetaQuotes Software Corp.

689

Standard Constants, Enumerations and Structures

Predefined Macro Substitutions


To simplify the debugging process and obtain information about operation of a mql5-program, there
are special macro constant, values of which are set at the moment of compilation. The easiest way to
use these constants is outputting values by the Print() function, as it's shown in the example.
Constant

Description

__DATE__

File compilation date without time (hours,


minutes and seconds are equal to 0)

__DATETIME__

File compilation date and time

__LINE__

Line number in the source code, in which the


macro is located

__FILE__

Name of the currently compiled file

__PATH__

An absolute path to the file that is currently


being compiled

__FUNCTION__

Name of the function, in whose body the macro


is located

__FUNCSIG__

Signature of the function in whose body the


macro is located. Logging of the full description
of functions can be useful in the identification
of overloaded functions

__MQLBUILD__, __MQL5BUILD__

Compiler build number

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

//--- set the interval between the timer events


EventSetTimer(5);
//--}
//+------------------------------------------------------------------+
//| Expert deinitialization function

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- an example of information output at Expert Advisor deinitialization
Print(" __FUNCTION__ = ",__FUNCTION__,"

__LINE__ = ",__LINE__);

2000-2016, MetaQuotes Software Corp.

690

Standard Constants, Enumerations and Structures


//--}
//+------------------------------------------------------------------+
//| Expert tick function

//+------------------------------------------------------------------+
void OnTick()
{
//--- information output at tick receipt
Print(" __MQLBUILD__ = ",__MQLBUILD__,"

__FILE__ = ",__FILE__);

Print(" __FUNCTION__ = ",__FUNCTION__,"

__LINE__ = ",__LINE__);

test1(__FUNCTION__);
test2();
//--}
//+------------------------------------------------------------------+
//| test1

//+------------------------------------------------------------------+
void test1(string par)
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__,"

__LINE__ = ",__LINE__," par = ",par);

}
//+------------------------------------------------------------------+
//| 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__);
}

2000-2016, MetaQuotes Software Corp.

691

Standard Constants, Enumerations and Structures

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

2000-2016, MetaQuotes Software Corp.

692

Standard Constants, Enumerations and Structures


}

2000-2016, MetaQuotes Software Corp.

693

Standard Constants, Enumerations and Structures

Numerical Type Constants


Each simple numerical type is intended for a certain type of tasks and allows optimizing the operation
of a mql5-program when used correctly. For a better code readability and correct handling of
calculation results, there are constants which allow to receive information about restrictions set to a
certain type of simple data.
Constant

Description

Value

CHAR_MIN

Minimal value, which can be


represented by char type

-128

CHAR_MAX

Maximal value, which can be


represented by char type

127

UCHAR_MAX

Maximal value, which can be


represented by uchar type

255

SHORT_MIN

Minimal value, which can be


represented by short type

-32768

SHORT_MAX

Maximal value, which can be


represented by short type

32767

USHORT_MAX

Maximal value, which can be


represented by ushort type

65535

INT_MIN

Minimal value, which can be


represented by int type

-2147483648

INT_MAX

Maximal value, which can be


represented by int type

2147483647

UINT_MAX

Maximal value, which can be


represented by uint type

4294967295

LONG_MIN

Minimal value, which can be


represented by long type

-9223372036854775808

LONG_MAX

Maximal value, which can be


represented by long type

9223372036854775807

ULONG_MAX

Maximal value, which can be


represented by ulong type

18446744073709551615

DBL_MIN

Minimal positive value, which


can be represented by double
type

2.2250738585072014e-308

DBL_MAX

Maximal value, which can be


represented by double type

1.7976931348623158e+308

DBL_EPSILON

Minimal value, which satisfies


the condition:
1.0+DBL_EPSILON != 1.0 (for
double type)

2.2204460492503131e-016

DBL_DIG

Number of significant decimal

15

2000-2016, MetaQuotes Software Corp.

694

Standard Constants, Enumerations and Structures


digits for double type
DBL_MANT_DIG

Number of bits in a mantissa


for double type

53

DBL_MAX_10_EXP

Maximal decimal value of


exponent degree for double
type

308

DBL_MAX_EXP

Maximal binary value of


exponent degree for double
type

1024

DBL_MIN_10_EXP

Minimal decimal value of


exponent degree for double
type

(-307)

DBL_MIN_EXP

Minimal binary value of


exponent degree for double
type

(-1021)

FLT_MIN

Minimal positive value, which


can be represented by float
type

1.175494351e-38

FLT_MAX

Maximal value, which can be


represented by float type

3.402823466e+38

FLT_EPSILON

Minimal value, which satisfies


the condition:
1.0+DBL_EPSILON != 1.0 (for
float type)

1.192092896e07

FLT_DIG

Number of significant decimal


digits for float type

FLT_MANT_DIG

Number of bits in a mantissa


for float type

24

FLT_MAX_10_EXP

Maximal decimal value of


exponent degree for float type

38

FLT_MAX_EXP

Maximal binary value of


exponent degree for float type

128

FLT_MIN_10_EXP

Minimal decimal value of


exponent degree for float type

-37

FLT_MIN_EXP

Minimal binary value of


exponent degree for float type

(-125)

Example:
void OnStart()
{
//--- print the constant values
printf("CHAR_MIN = %d",CHAR_MIN);

2000-2016, MetaQuotes Software Corp.

695

Standard Constants, Enumerations and Structures


printf("CHAR_MAX = %d",CHAR_MAX);
printf("UCHAR_MAX = %d",UCHAR_MAX);
printf("SHORT_MIN = %d",SHORT_MIN);
printf("SHORT_MAX = %d",SHORT_MAX);
printf("USHORT_MAX = %d",USHORT_MAX);
printf("INT_MIN = %d",INT_MIN);
printf("INT_MAX = %d",INT_MAX);
printf("UINT_MAX = %u",UINT_MAX);
printf("LONG_MIN = %I64d",LONG_MIN);
printf("LONG_MAX = %I64d",LONG_MAX);
printf("ULONG_MAX = %I64u",ULONG_MAX);
printf("EMPTY_VALUE = %.16e",EMPTY_VALUE);
printf("DBL_MIN = %.16e",DBL_MIN);
printf("DBL_MAX = %.16e",DBL_MAX);
printf("DBL_EPSILON = %.16e",DBL_EPSILON);
printf("DBL_DIG = %d",DBL_DIG);
printf("DBL_MANT_DIG = %d",DBL_MANT_DIG);
printf("DBL_MAX_10_EXP =

%d",DBL_MAX_10_EXP);

printf("DBL_MAX_EXP = %d",DBL_MAX_EXP);
printf("DBL_MIN_10_EXP = %d",DBL_MIN_10_EXP);
printf("DBL_MIN_EXP = %d",DBL_MIN_EXP);
printf("FLT_MIN = %.8e",FLT_MIN);
printf("FLT_MAX = %.8e",FLT_MAX);
printf("FLT_EPSILON = %.8e",FLT_EPSILON);
}

2000-2016, MetaQuotes Software Corp.

696

Standard Constants, Enumerations and Structures

Uninitialization Reason Codes


Uninitialization reason codes are returned by the UninitializeReason() function. The possible values are
the following:
Constant

Value

Description

REASON_PROGRAM

Expert Advisor terminated its


operation by calling the
ExpertRemove() function

REASON_REMOVE

Program has been


from the chart

REASON_RECOMPILE

Program has been recompiled

REASON_CHARTCHANGE

Symbol or chart period has


been changed

REASON_CHARTCLOSE

Chart has been closed

REASON_PARAMETERS

Input parameters have been


changed by a user

REASON_ACCOUNT

Another account has been


activated or reconnection to
the trade server has occurred
due to changes in the account
settings

REASON_TEMPLATE

A new template has


applied

REASON_INITFAILED

This value means that OnInit()


handler has returned a nonzero
value

REASON_CLOSE

Terminal has been closed

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;

2000-2016, MetaQuotes Software Corp.

697

Standard Constants, Enumerations and Structures


case REASON_CHARTCHANGE:
text="Symbol or timeframe was changed";break;
case REASON_CHARTCLOSE:
text="Chart was closed";break;
case REASON_PARAMETERS:
text="Input-parameter was changed";break;
case REASON_RECOMPILE:
text="Program "+__FILE__+" was recompiled";break;
case REASON_REMOVE:
text="Program "+__FILE__+" was removed from chart";break;
case REASON_TEMPLATE:
text="New template was applied to chart";break;
default:text="Another reason";
}
//--return text;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- The first way to get the uninitialization reason code
Print(__FUNCTION__,"_Uninitalization reason code = ",reason);
//--- The second way to get the uninitialization reason code
Print(__FUNCTION__,"_UninitReason = ",getUninitReasonText(_UninitReason));
}

2000-2016, MetaQuotes Software Corp.

698

Standard Constants, Enumerations and Structures

Checking Object Pointer


The CheckPointer() function is used for checking the type of the object pointer. The function returns a
value of the ENUM_POINTER_TYPE enumeration. If an incorrect pointer is used, the program execution
will be immediately terminated.
Objects created by the new() operator are of POINTER_DYNAMIC type. The delete() operator can and
should be used only for such pointers.
All other pointers are of POINTER_AUTOMATIC type, which means that this object has been created
automatically by the mql5 program environment. Such objects are deleted automatically after being
used.
ENUM_POINTER_TYPE
Constant

Description

POINTER_INVALID

Incorrect pointer

POINTER_DYNAMIC

Pointer of the object created by the new()


operator

POINTER_AUTOMATIC

Pointer of any objects created automatically


(not using new())

See also
Runtime errors, Object Delete Operator delete, CheckPointer

2000-2016, MetaQuotes Software Corp.

699

Standard Constants, Enumerations and Structures

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

Empty value in an indicator


buffer

DBL_MAX

INVALID_HANDLE

Incorrect handle

-1

IS_DEBUG_MODE

Flag that a mq5-program


operates in debug mode

non zero in debug


otherwise zero

IS_PROFILE_MODE

Flag that a mq5-program


operates in profiling mode

non zero in profiling mode,


otherwise zero

NULL

Zero for any types

WHOLE_ARRAY

Means the number of items


remaining until the end of the
array, i.e., the entire array
will be processed

-1

WRONG_VALUE

The constant can be implicitly


cast to any enumeration type

-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

2000-2016, MetaQuotes Software Corp.

700

Standard Constants, Enumerations and Structures


ObjectGetInteger() the result is true, a value from ENUM_LINE_STYLE is returned; otherwise
WRONG_VALUE is returned.
void OnStart()
{
if(CheckLineStyle("MyChartObject")==WRONG_VALUE)
printf("Error line style getting.");
}
//+------------------------------------------------------------------+
//| returns the line style for an object specified by its name

//+------------------------------------------------------------------+
ENUM_LINE_STYLE CheckLineStyle(string name)
{
long style;
//--if(ObjectGetInteger(0,name,OBJPROP_STYLE,0,style))
return((ENUM_LINE_STYLE)style);
else
return(WRONG_VALUE);
}

The WHOLE_ARRAY constant is intended 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

2000-2016, MetaQuotes Software Corp.

701

Standard Constants, Enumerations and Structures


running mode. In order to run a script in the debug mode from MetaEditor, press F5. If you run the
script from the browser window in the terminal, then the color and text of the object Label will be
different.
Example:
//+------------------------------------------------------------------+
//|

Check_DEBUG_MODE.mq5 |

//|

Copyright 2009, MetaQuotes Software Corp. |

//|

http://www.metaquotes.net |

//+------------------------------------------------------------------+
#property copyright "Copyright 2009, MetaQuotes Software Corp."
#property link

"http://www.metaquotes.net"

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

// here termination will occur, if we are in debug mode

}
}

2000-2016, MetaQuotes Software Corp.

702

Standard Constants, Enumerations and Structures

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

AES encryption with 128 bit key (16 bytes)

CRYPT_AES256

AES encryption with 256 bit key (32 bytes)

CRYPT_DES

DES encryption with 56 bit key (7 bytes)

CRYPT_HASH_SHA1

SHA1 HASH calculation

CRYPT_HASH_SHA256

SHA256 HASH calculation

CRYPT_HASH_MD5

MD5 HASH calculation

CRYPT_ARCH_ZIP

ZIP archives

See also
See also
DebugBreak, Executed MQL5 program properties, CryptEncode(), CryptDecode()

2000-2016, MetaQuotes Software Corp.

703

Standard Constants, Enumerations and Structures

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,

volume and spread;


MqlBookInfo is intended for obtaining information about the Depth of Market;
MqlTradeRequest is used for creating a trade request for trade operations;
MqlTradeCheckResult is intended for checking the prepared trade request before sending it;
MqlTradeResult contains a trade server reply to a trade request, sent by OrderSend() function;
MqlTradeTransaction contains description of a trade transaction;
MqlTick is designed for fast retrieval of the most requested information about current prices.

2000-2016, MetaQuotes Software Corp.

704

Standard Constants, Enumerations and Structures

MqlDateTime
The date type structure contains eight fields of the int type:
struct MqlDateTime
{
int year;

// Year

int mon;

// Month

int day;

// Day

int hour;

// Hour

int min;

// Minutes

int sec;

// Seconds

int day_of_week;

// Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)

int day_of_year;

// Day number of the year (January 1st is assigned the number value of zero)

};

Note
The day number of the year day_of_year for the leap year, since March, will differ from a number of
the corresponding day for a non-leap year.
Example:
void OnStart()
{
//--datetime date1=D'2008.03.01';
datetime date2=D'2009.03.01';
MqlDateTime str1,str2;
TimeToStruct(date1,str1);
TimeToStruct(date2,str2);
printf("%02d.%02d.%4d, day of year = %d",str1.day,str1.mon,
str1.year,str1.day_of_year);
printf("%02d.%02d.%4d, day of year = %d",str2.day,str2.mon,
str2.year,str2.day_of_year);
}
/*

Result:
01.03.2008, day of year = 60
01.03.2009, day of year = 59

*/

See also
TimeToStruct, Structures and Classes

2000-2016, MetaQuotes Software Corp.

705

Standard Constants, Enumerations and Structures

The Structure of Input Parameters of Indicators (MqlParam)


The MqlParam structure has been specially designed to provide input parameters when creating the
handle of a technical indicator using the IndicatorCreate() function.
struct MqlParam
{
ENUM_DATATYPE

type;

// type of the input parameter, value of ENUM_DATATYP

long

integer_value;

// field to store an integer type

double

double_value;

// field to store a double type

string

string_value;

// field to store a string type

};

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.

2000-2016, MetaQuotes Software Corp.

706

Standard Constants, Enumerations and Structures

MqlRates
This structure stores information about the prices, volumes and spread.
struct MqlRates
{
datetime time;

// Period start time

double

open;

// Open price

double

high;

// The highest price of the period

double

low;

// The lowest price of the period

double

close;

// Close price

long

tick_volume;

// Tick volume

int

spread;

// Spread

long

real_volume;

// Trade volume

};

Example:
void OnStart()
{
MqlRates rates[];
int copied=CopyRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Error copying price data ",GetLastError());
else Print("Copied ",ArraySize(rates)," bars");
}

See also
CopyRates, Access to timeseries

2000-2016, MetaQuotes Software Corp.

707

Standard Constants, Enumerations and Structures

MqlBookInfo
It provides information about the market depth data.
struct MqlBookInfo
{
ENUM_BOOK_TYPE

type;

// Order type from ENUM_BOOK_TYPE enumeration

double

price;

// Price

long

volume;

// Volume

};

Note
The 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

2000-2016, MetaQuotes Software Corp.

708

Standard Constants, Enumerations and Structures

The Trade Request Structure (MqlTradeRequest)


Interaction between the client terminal and a trade server for executing the order placing operation is
performed by using trade requests. The trade request is represented by the special predefined
structure of MqlTradeRequest type, which contain all the fields necessary to perform trade deals. The
request processing result is represented by the structure of MqlTradeResult type.
struct MqlTradeRequest
{
ENUM_TRADE_REQUEST_ACTIONS

action;

// Trade operation type

ulong

magic;

// Expert Advisor ID (magic number)

ulong

order;

// Order ticket

string

symbol;

// Trade symbol

double

volume;

// Requested volume for a deal in lots

double

price;

// Price

double

stoplimit;

// StopLimit level of the order

double

sl;

// Stop Loss level of the order

double

tp;

// Take Profit level of the order

ulong

deviation;

// Maximal possible deviation from the requested

ENUM_ORDER_TYPE

type;

// Order type

ENUM_ORDER_TYPE_FILLING

type_filling;

// Order execution type

ENUM_ORDER_TYPE_TIME

type_time;

// Order expiration type

datetime

expiration;

// Order expiration time (for the orders of ORDE

string

comment;

// Order comment

ulong

position;

// Position ticket

ulong

position_by;

// The ticket of an opposite position

};

Fields description
Field

Description

action

Trade operation type. Can be one of the


ENUM_TRADE_REQUEST_ACTIONS enumeration
values.

magic

Expert Advisor ID. It allows organizing analytical


processing of trade orders. Each Expert Advisor
can set its own unique ID when sending a trade
request.

order

Order ticket. It is used for modifying pending


orders.

symbol

Symbol of the order. It is not necessary for


order modification and position
close
operations.

volume

Requested order volume in lots. Note that the


real volume of a deal will depend on the order
execution type.

2000-2016, MetaQuotes Software Corp.

709

Standard Constants, Enumerations and Structures

price

Price, reaching which the order must be


executed. Market orders of symbols, whose
execution
type
is
"Market
Execution" (SYMBOL_TRADE_EXECUTION_MARK
ET), of TRADE_ACTION_DEAL type, do not
require specification of price.

stoplimit

The price value, at which the Limit pending


order will be placed, when price reaches the
price value (this condition is obligatory). Until
then the pending order is not placed.

sl

Stop Loss price in case of the unfavorable price


movement

tp

Take Profit price in the case of the favorable


price movement

deviation

The maximal price deviation, specified in


points

type

Order
type.
Can
be
one
of
ENUM_ORDER_TYPE enumeration values.

type_filling

Order execution type. Can be one of the


enumeration
ENUM_ORDER_TYPE_FILLING
values.

type_time

Order expiration type. Can be one of the


enumeration ENUM_ORDER_TYPE_TIME values.

expiration

Order expiration time (for


ORDER_TIME_SPECIFIED type)

comment

Order comment

position

Ticket of a position. Should be filled in when a


position is modified or closed to identify the
position. As a rule it is equal to the ticket of
the order, based on which the position was
opened.

position_by

Ticket of an opposite position. Used when a


position is closed by an opposite one open for
the same symbol in the opposite direction.

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

2000-2016, MetaQuotes Software Corp.

710

Standard Constants, Enumerations and Structures


This is a trade order to open a position in the Request Execution mode (trade upon requested
prices). It requires to specify the following 9 fields:
action
symbol
volume
price
sl
tp
deviation
type
type_filling

Also it is possible to specify the "magic" and "comment" field values.


Instant Execution
This is a trade order to open a position in the Instant Execution mode (trade by current prices). It
requires specification of the following 9 fields:
action
symbol
volume
price
sl
tp
deviation
type
type_filling

Also it is possible to specify the "magic" and "comment" field values.


Market Execution
This is a trade order to open a position in the Market Execution mode. It requires to specify the
following 5 fields:
action
symbol
volume
type
type_filling

Also it is possible to specify the "magic" and "comment" field values.


Exchange Execution
This is a trade order to open a position in the Exchange Execution mode. It requires to specify the
following 5 fields:
action
symbol
volume
type
type_filling
2000-2016, MetaQuotes Software Corp.

711

Standard Constants, Enumerations and Structures


Also it is possible to specify the "magic" and "comment" field values.
SL & TP Modification
Trade order to modify the StopLoss and/or TakeProfit price levels. It requires to specify the
following 4 fields:
action
symbol
sl
tp
position

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

Also it is possible to specify the "magic" and "comment" field values.


Modify Pending Order
Trade order to modify the prices of a pending order. It requires to specify the following 7 fields:
action
order
price
sl
tp
type_time
expiration

Delete Pending Order


Trade order to delete a pending order. It requires to specify the following 2 fields:
action
order

See also
Structures and Classes, Trade Functions, Order Properties

2000-2016, MetaQuotes Software Corp.

712

Standard Constants, Enumerations and Structures

The Structure of Results of a Trade Request Check


(MqlTradeCheckResult)
Before sending a request for a trade operation to a trade server, it is recommended to check it. The
check is performed using the OrderCheck() function, to which the checked request and a variable of
the MqlTradeCheckResult structure type are passed. The check result will be written to this variable.
struct MqlTradeCheckResult
{
uint

retcode;

// Reply code

double

balance;

// Balance after the execution of the deal

double

equity;

// Equity after the execution of the deal

double

profit;

// Floating profit

double

margin;

// Margin requirements

double

margin_free;

// Free margin

double

margin_level;

// Margin level

string

comment;

// Comment to the reply code (description of the error)

};

Description of Fields
Field

Description

retcode

Return code

balance

Balance value that will be after the execution of


the trade operation

equity

Equity value that will be after the execution of


the trade operation

profit

Value of the floating profit that will be after the


execution of the trade operation

margin

Margin required for the trade operation

margin_free

Free margin that will be left after the execution


of the trade operation

margin_level

Margin level that will be set after the execution


of the trade operation

comment

Comment to the reply code, error description

See also
Trade Request Structure, Structure for Current Prices, OrderSend, OrderCheck

2000-2016, MetaQuotes Software Corp.

713

Standard Constants, Enumerations and Structures

The Structure of a Trade Request Result (MqlTradeResult)


As result of a trade request, a trade server returns data about the trade request processing result as a
special predefined structure of MqlTradeResult type.
struct MqlTradeResult
{
uint

retcode;

// Operation return code

ulong

deal;

// Deal ticket, if it is performed

ulong

order;

// Order ticket, if it is placed

double

volume;

// Deal volume, confirmed by broker

double

price;

// Deal price, confirmed by broker

double

bid;

// Current Bid price

double

ask;

// Current Ask price

string

comment;

// Broker comment to operation (by default it is filled by descriptio

uint

request_id;

// Request ID set by the terminal during the dispatch

};

Fields description
Field

Description

retcode

Return code of a trade server

deal

Deal ticket, if a deal has been performed. It is


available
for
a
trade
operation
of
TRADE_ACTION_DEAL type

order

Order ticket, if a ticket has been placed. It is


available for a trade operation of
TRADE_ACTION_PENDING type

volume

Deal volume, confirmed by broker. It depends


on the order filling type

price

Deal price, confirmed by broker. It depends on


the deviation field of the trade request and/or
on the trade operation

bid

The current market Bid price (requote price)

ask

The current market Ask price (requote price)

comment

The broker comment to operation (by default it


is filled by description of trade server return
code)

request_id

Request ID set by the terminal when sending to


the trade server

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.

2000-2016, MetaQuotes Software Corp.

714

Standard Constants, Enumerations and Structures


The terminal fixes request ID in request_id field when sending it to the trade server using
OrdersSend() and OrderSendAsync() functions. The terminal receives messages about performed
transactions from the trade server and submits them for processing by OnTradeTransaction() function
containing the following components as parameters:
description of the trade transaction inMqlTradeTransaction structure;
description of the trade request sent from OrderSend() or OrdersSendAsync() function. Request ID is

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 = ",

result.ask," result.bid = ",result.bid);


break;
}
//--- order is not accepted by the server
case 10006:

2000-2016, MetaQuotes Software Corp.

715

Standard Constants, Enumerations and Structures


{
Print("TRADE_RETCODE_REJECT");
Print("request.price = ",request.price,"

result.ask = ",

result.ask," result.bid = ",result.bid);


break;
}
//--- invalid price
case 10015:
{
Print("TRADE_RETCODE_INVALID_PRICE");
Print("request.price = ",request.price,"

result.ask = ",

result.ask," result.bid = ",result.bid);


break;
}
//--- invalid SL and/or TP
case 10016:
{
Print("TRADE_RETCODE_INVALID_STOPS");
Print("request.sl = ",request.sl," request.tp = ",request.tp);
Print("result.ask = ",result.ask," result.bid = ",result.bid);
break;
}
//--- invalid volume
case 10014:
{
Print("TRADE_RETCODE_INVALID_VOLUME");
Print("request.volume = ",request.volume,"

result.volume = ",

result.volume);
break;
}
//--- not enough money for a trade operation
case 10019:
{
Print("TRADE_RETCODE_NO_MONEY");
Print("request.volume = ",request.volume,"
result.volume,"

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

2000-2016, MetaQuotes Software Corp.

716

Standard Constants, Enumerations and Structures


}

2000-2016, MetaQuotes Software Corp.

717

Standard Constants, Enumerations and Structures

Structure of a Trade Transaction (MqlTradeTransaction)


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

OrderSendAsync functions and its further execution;


Sending a trade request via the terminal graphical interface and its further execution;
Pending orders and stop orders activation on the server;
Performing operations on a trade server side.

The following trade transactions are performed as a result of these actions:


handling a trade request;
changing open orders;
changing orders history;
changing deals history;
changing positions.

For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
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;

// Trade symbol name

ENUM_TRADE_TRANSACTION_TYPE

type;

// Trade transaction 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;

// Order type by action period

datetime

time_expiration;

// Order expiration time

double

price;

// Price

double

price_trigger;

// Stop limit order activation price

double

price_sl;

// Stop Loss level

double

price_tp;

// Take Profit level

double

volume;

// Volume in lots

ulong

position;

// Position ticket

ulong

position_by;

// Ticket of an opposite position

};

Fields Description

2000-2016, MetaQuotes Software Corp.

718

Standard Constants, Enumerations and Structures

Field

Description

deal

Deal ticket.

order

Order ticket.

symbol

The name of the trading symbol, for which


transaction is performed.

type

Trade transaction type. The value can be one


of
ENUM_TRADE_TRANSACTION_TYPE
enumeration values.

order_type

Trade order type. The value can be one of


ENUM_ORDER_TYPE enumeration values.

order_state

Trade order state. The value can be one of


ENUM_ORDER_STATE enumeration values.

deal_type

Deal type. The value can be one


ENUM_DEAL_TYPE enumeration values.

type_time

Order type upon expiration. The value can be


one of ENUM_ORDER_TYPE_TIME values.

time_expiration

Pending order expiration term (for orders of


ORDER_TIME_SPECIFIED
and
ORDER_TIME_SPECIFIED_DAY types).

price

Price. Depending on a trade transaction type, it


may be a price of an order, a deal or a position.

price_trigger

Stop limit order stop (activation)


(ORDER_TYPE_BUY_STOP_LIMIT
ORDER_TYPE_SELL_STOP_LIMIT).

price_sl

Stop Loss price. Depending on a trade


transaction type, it may relate to an order, a
deal or a position.

price_tp

Take Profit price. Depending on a trade


transaction type, it may relate to an order, a
deal or a position.

volume

Volume in lots. Depending on a trade


transaction type, it may indicate the current
volume of an order, a deal or a position.

position

The ticket of the position affected by the


transaction.

position_by

The ticket of the opposite position Used when


closing a position by an opposite one, i.e. by a
position of the same symbol that was opened in
the opposite direction.

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

2000-2016, MetaQuotes Software Corp.

719

Standard Constants, Enumerations and Structures


request by the server has been received), the structure has only only one field that is filled completely
- type. Other fields are not analyzed. In this case, we may analyze two additional request and result
parameters submitted to OnTradeTransaction() handler, as shown below.
Having data on a trading operation type, you can decide on the analysis of the current state of orders,
positions and deals on a trading account. Remember that one trade request sent to the server from
the terminal can generate several new transactions. The priority of their arrival at the terminal is not
guaranteed.
MqlTradeTransaction structure is filled in different ways depending on a trade transaction type
(ENUM_TRADE_TRANSACTION_TYPE):
TRADE_TRANSACTION_ORDER_* and TRADE_TRANSACTION_HISTORY_*
The following fields in MqlTradeTransaction structure are filled for trade transactions related to
open orders handling (TRADE_TRANSACTION_ORDER_ADD, TRADE_TRANSACTION_ORDER_UPDATE
and
TRADE_TRANSACTION_ORDER_DELETE)
and
orders
history
(TRADE_TRANSACTION_HISTORY_ADD,
TRADE_TRANSACTION_HISTORY_UPDATE,
TRADE_TRANSACTION_HISTORY_DELETE):
order - order ticket;
symbol - order symbol name;
type - trade transaction type;
order_type - order type;
orders_state - order current state;
time_type - order expiration type;
time_expiration - order expiration time (for orders

having ORDER_TIME_SPECIFIED and

ORDER_TIME_SPECIFIED_DAY expiration types);


price - order price specified by a client;
price_trigger - stop limit order stop price (only for ORDER_TYPE_BUY_STOP_LIMIT

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

using HistoryOrders* function.


position - the ticket of the position that was opened, modified or closed as a result of order

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

position by an opposite one).


TRADE_TRANSACTION_DEAL_*
The following fields in MqlTradeTransaction structure are filled for trade transactions related to
deals handling (TRADE_TRANSACTION_DEAL_ADD, TRADE_TRANSACTION_DEAL_UPDATE and
TRADE_TRANSACTION_DEAL_DELETE):
deal - deal ticket;
order - order ticket, based on which a deal has been performed;
symbol - deal symbol name;
type - trade transaction type;
deal_type - deal type;
price - deal price;

2000-2016, MetaQuotes Software Corp.

720

Standard Constants, Enumerations and Structures


price_sl - Stop Loss price (filled, if specified in the order, based on which a deal has been

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 by an opposite one).


TRADE_TRANSACTION_POSITION
The following fields in MqlTradeTransaction structure are filled for trade transactions related to
changing the positions not connected with deals execution (TRADE_TRANSACTION_POSITION):
symbol - position symbol name;
type - trade transaction type;
deal_type - position type (DEAL_TYPE_BUY or DEAL_TYPE_SELL);
price - weighted average position open price;
price_sl - Stop Loss price;
price_tp - Take Profit price;
volume - position volume in lots, if it has been changed.

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

2000-2016, MetaQuotes Software Corp.

721

Standard Constants, Enumerations and Structures


//+------------------------------------------------------------------+
int OnInit()
{
//--- set MagicNumber to mark all our orders
trade.SetExpertMagicNumber(MagicNumber);
//--- trade requests will be sent in asynchronous mode using OrderSendAsync() function
trade.SetAsyncMode(true);
//--- initialize the variable by zero
order_ticket=0;
//--return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function

//+------------------------------------------------------------------+
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)

2000-2016, MetaQuotes Software Corp.

722

Standard Constants, Enumerations and Structures


{
pending_deleted=true;
//--- get the request execution result
MqlTradeResult trade_result;
trade.Result(trade_result);
//--- take request ID from the result
uint request_id=trade_result.request_id;
//--- display in Journal
Print("The request has been sent to delete a pending order #",order_ticket,
". Request_ID=",request_id,
"\r\n");
//--- fix the order ticket from the request result
order_ticket=trade_result.order;
}
}
//--}
//+------------------------------------------------------------------+
//| TradeTransaction function

//+------------------------------------------------------------------+
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));
//--}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

723

Standard Constants, Enumerations and Structures


//| Returns transaction textual description

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

2000-2016, MetaQuotes Software Corp.

724

Standard Constants, Enumerations and Structures


//| Returns the textual description of the request handling result

//+------------------------------------------------------------------+
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()

2000-2016, MetaQuotes Software Corp.

725

Standard Constants, Enumerations and Structures

The Structure for Returning Current Prices (MqlTick)


This is a structure for storing the latest prices of the symbol. It is designed for fast retrieval of the
most requested information about current prices.
struct MqlTick
{
datetime

time;

// Time of the last prices update

double

bid;

// Current Bid price

double

ask;

// Current Ask price

double

last;

// Price of the last deal (Last)

ulong

volume;

// Volume for the current Last price

long

time_msc;

// Time of a price last update in milliseconds

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

Standard Constants, Enumerations and Structures

Codes of Errors and Warnings


This section contains the following descriptions:
Return codes of the trade server analyzing results of the trade request sent by function

OrderSend();
Compiler warnings codes of warning messages that appear at compilation (not errors);
Compilation errors codes of error messages at an unsuccessful attempt to compile;
Runtime errors error codes in the execution of mql5-programs, which can be obtained using the

GetLastError() function.

2000-2016, MetaQuotes Software Corp.

727

Standard Constants, Enumerations and Structures

Return Codes of the Trade Server


All requests to execute trade operations are sent as a structure of a trade request MqlTradeRequest
using function OrderSend(). The function execution result is placed to structure MqlTradeResult,
whose retcode field contains the trade server return code.
Code

Constant

Description

10004

TRADE_RETCODE_REQUOTE

Requote

10006

TRADE_RETCODE_REJECT

Request rejected

10007

TRADE_RETCODE_CANCEL

Request canceled by trader

10008

TRADE_RETCODE_PLACED

Order placed

10009

TRADE_RETCODE_DONE

Request completed

10010

TRADE_RETCODE_DONE_PARTI
AL

Only part of the request was


completed

10011

TRADE_RETCODE_ERROR

Request processing error

10012

TRADE_RETCODE_TIMEOUT

Request canceled by timeout

10013

TRADE_RETCODE_INVALID

Invalid request

10014

TRADE_RETCODE_INVALID_VOL
UME

Invalid volume in the request

10015

TRADE_RETCODE_INVALID_PRI
CE

Invalid price in the request

10016

TRADE_RETCODE_INVALID_STO
PS

Invalid stops in the request

10017

TRADE_RETCODE_TRADE_DISA
BLED

Trade is disabled

10018

TRADE_RETCODE_MARKET_CL
OSED

Market is closed

10019

TRADE_RETCODE_NO_MONEY

There is not enough money to


complete the request

10020

TRADE_RETCODE_PRICE_CHAN
GED

Prices changed

10021

TRADE_RETCODE_PRICE_OFF

There are no quotes to process


the request

10022

TRADE_RETCODE_INVALID_EXPI
RATION

Invalid order expiration date in


the request

10023

TRADE_RETCODE_ORDER_CHA
NGED

Order state changed

10024

TRADE_RETCODE_TOO_MANY_
REQUESTS

Too frequent requests

2000-2016, MetaQuotes Software Corp.

728

Standard Constants, Enumerations and Structures


10025

TRADE_RETCODE_NO_CHANGE
S

No changes in request

10026

TRADE_RETCODE_SERVER_DISA
BLES_AT

Autotrading disabled by server

10027

TRADE_RETCODE_CLIENT_DISA
BLES_AT

Autotrading disabled by client


terminal

10028

TRADE_RETCODE_LOCKED

Request locked for processing

10029

TRADE_RETCODE_FROZEN

Order or position frozen

10030

TRADE_RETCODE_INVALID_FILL

Invalid order filling type

10031

TRADE_RETCODE_CONNECTION

No connection with the trade


server

10032

TRADE_RETCODE_ONLY_REAL

Operation is allowed only for


live accounts

10033

TRADE_RETCODE_LIMIT_ORDE
RS

The number of pending orders


has reached the limit

10034

TRADE_RETCODE_LIMIT_VOLU
ME

The volume of orders and


positions for the symbol has
reached the limit

10035

TRADE_RETCODE_INVALID_ORD
ER

Incorrect or prohibited order


type

10036

TRADE_RETCODE_POSITION_CL
OSED

Position with the specified


POSITION_IDENTIFIER
has
already been closed

2000-2016, MetaQuotes Software Corp.

729

Standard Constants, Enumerations and Structures

Compiler Warnings
Compiler warnings are shown for informational purposes only and are not error messages.
Code

Description
21

Incomplete record of a date in the datetime


string

22

Wrong number in the datetime string for the


date. Requirements:
Year 1970 <= X <= 3000
Month 0 <X <= 12
Day 0 <X <= 31/30/28 (29 )....

23

Wrong number of datetime string for time.


Requirements:
Hour 0 <= X <24
Minute 0 <= X <60

24

Invalid color in RGB format: one of RGB


components is less than 0 or greater than 255

25

Unknown character of the escape sequences.


Known: \n \r \t \\ \" \' \X \x

26

Too large volume of local variables (> 512Kb) of


the function, reduce the number

29

Enumeration already defined (duplication) members will be added to the first definition

30

Overriding macro

31

The variable is declared but is not used


anywhere

32

Constructor must be of void type

33

Destructor must be of void type

34

Constant does not fit in the range of integers


(X> _UI64_MAX | | X <_I64_MIN) and will be
converted to the double type

35

Too long HEX - more than 16 significant


characters (senior nibbles are cut)

36

No nibbles in HEX string "0x"

37

No function - nothing to be performed

38

A non-initialized variable is used

41

Function has no body, and is not called

43

Possible loss of data at typecasting. Example:


int x = (double) z;

2000-2016, MetaQuotes Software Corp.

730

Standard Constants, Enumerations and Structures

44

Loss of accuracy (of data) when converting a


constant. Example: int x = M_PI

45

Difference between the signs of operands in the


operations of comparison. Example: (char) c1>
(uchar) c2

46

Problems with function importing - declaration


of #import is required or import of functions is
closed

47

Too large description - extra characters will not


be included in the executable file

48

The number of indicator buffers declared is less


than required

49

No color to plot a graphical series in the


indicator

50

No graphical series to draw the indicator

51

'OnStart' handler function not found in the script

52

'OnStart' handler function is defined with wrong


parameters

53

'OnStart' function can be defined only in a script

54

'OnInit' function
parameters

55

'OnInit' function is not used in scripts

56

'OnDeinit' function is
parameters

57

'OnDeinit' function is not used in scripts

58

Two 'OnCalculate' functions are defined.


OnCalculate () at one price array will be used

59

Overfilling detected when calculating a complex


integer constant

60

Probably, the variable is not initialized.

61

This declaration makes it impossible to refer to


the local variable declared on the specified line

62

This declaration makes it impossible to refer to


the global variable declared on the specified
line

63

Cannot be used for static allocated array

64

65

This variable
variable

is

defined

with

defined with

declaration

hides

wrong

wrong

predefined

The value of the expression is always true/false

2000-2016, MetaQuotes Software Corp.

731

Standard Constants, Enumerations and Structures

66

Using a variable or bool type expression in


mathematical operations is unsafe

67

The result of applying the unary minus operator


to an unsigned ulong type is undefined

68

The version specified in the #property version


property is unacceptable for the Market section;
the correct format of #property version id
"XXX.YYY"

69

Empty controlled statement found

70

Invalid function return type or incorrect


parameters during declaration of the event
handler function

71

An implicit cast of structures to one type is


required

72

This declaration makes direct access to the


member of a class declared in the specified
string impossible. Access will be possible only
with the scope resolution operation ::

73

Binary constant is too big, high-order digits will


be truncated

74

Parameter in the method of the inherited class


has a different const modifier, the derived
function has overloaded the parent function

75

Negative or too large shift value in shift bitwise


operation, execution result is undefined

76

Function must return a value

77

void function returns a value

78

Not all control paths return a value

79

Expressions are not allowed on a global scope

80

Check operator precedence for possible error;


use parentheses to clarify precedence

81

Two OnCalCulate() are defined. OHLC version


will be used

82

Struct has no members, size assigned to 1 byte

83

Return value of the function should be checked

84

Resource indicator is compiled for debugging.


That slows down the performance. Please
recompile the indicator to increase performance

85

Too great character code in the string, must be


in the range 0 to 65535

2000-2016, MetaQuotes Software Corp.

732

Standard Constants, Enumerations and Structures

86

Unrecognized character in the string

87

No indicator window property (setting the


display in the main window or a subwindow) is
defined.
Property
#property
indicator_chart_window is applied

2000-2016, MetaQuotes Software Corp.

733

Standard Constants, Enumerations and Structures

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

File reading error

101

Error of opening an *. EX5 for writing

103

Not enough free memory to complete


compilation

104

Empty syntactic unit unrecognized by compiler

105

Incorrect file name in #include

106

Error accessing a file in #include (probably the


file does not exist)

108

Inappropriate name for #define

109

Unknown command of preprocessor (valid


#include, #define, #property, #import)

110

Symbol unknown to compiler

111

Function not implemented (description is


present, but no body)

112

Double quote (") omitted

113

Opening angle bracket (<) or double quote (")


omitted

114

Single quote (') omitted

115

Closing angle bracket ">" omitted

116

Type not specified in declaration

117

No return operator or return is found not in all


branches of the implementation

118

Opening bracket of call parameters was


expected

119

Error writing EX5

120

Invalid access to an array

121

The function is not of void type and the return


operator must return a value

122

Incorrect declaration of the destructor

123

Colon ":" is missing

2000-2016, MetaQuotes Software Corp.

734

Standard Constants, Enumerations and Structures

124

Variable is already declared

125

Variable with such identifier already declared

126

Variable name is too long (> 250 characters)

127

Structure with such identifier already defined

128

Structure is not defined

129

Structure member with the same name already


defined

130

No such structure member

131

Breached pairing of brackets

132

Opening parenthesis "(" expected

133

Unbalanced braces (no "}")

134

Difficult to compile (too much branching,


internal stack levels are overfilled)

135

Error of file opening for reading

136

Not enough memory to download the source file


into memory

137

Variable is expected

138

Reference cannot be initialized

140

Assignment expected (appears at declaration)

141

Opening brace "{" expected

142

Parameter can be a dynamic array only

143

Use of "void" type is unacceptable

144

No pair for ")" or "]", i.e. "(or" [ " is absent

145

No pair for "(or" [ ", i.e. ") "or"] " is absent

146

Incorrect array size

147

Too many parameters (> 64)

149

This token is not expected here

150

Invalid use of operation (invalid operands)

151

Expression of void type not allowed

152

Operator is expected

153

Misuse of break

154

Semicolon ";" expected

155

Comma "," expected

156

Must be a class type, not struct

2000-2016, MetaQuotes Software Corp.

735

Standard Constants, Enumerations and Structures

157

Expression is expected

158

"non HEX character" found in HEX or too long


number (number of digits> 511)

159

String-constant has more than 65534 characters

160

Function definition is unacceptable here

161

Unexpected end of program

162

Forward declaration is prohibited for structures

163

Function with this name is already defined and


has another return type

164

Function with this name is already defined and


has a different set of parameters

165

Function with this name is already defined and


implemented

166

Function overload for this call was not found

167

Function with a return value of void type cannot


return a value

168

Function is not defined

170

Value is expected

171

In case expression only integer constants are


valid

172

The value of case in this switch is already used

173

Integer is expected

174

In #import expression file name is expected

175

Expressions are not allowed on global level

176

Omitted parenthesis ")" before ";"

177

To the left of equality sign a variable is


expected

178

The result of expression is not used

179

Declaring of variables is not allowed in case

180

Implicit conversion from a string to a number

181

Implicit conversion of a number to a string

182

Ambiguous call of an overloaded function


(several overloads fit)

183

Illegal else without proper if

184

Invalid case or default without a switch

2000-2016, MetaQuotes Software Corp.

736

Standard Constants, Enumerations and Structures

185

Inappropriate use of ellipsis

186

The initializing sequence has more elements


than the initialized variable

187

A constant for case expected

188

A constant expression required

189

A constant variable cannot be changed

190

Closing bracket or a comma is expected


(declaring array member)

191

Enumerator identifier already defined

192

Enumeration cannot have access modifiers


(const, extern, static)

193

Enumeration member already declared with a


different value

194

There is a variable defined with the same name

195

There is a structure defined with the same


name

196

Name of enumeration member expected

197

Integer expression expected

198

Division by zero in constant expression

199

Wrong number of parameters in the function

200

Parameter by reference must be a variable

201

Variable of the same type to pass by reference


expected

202

A constant variable cannot be passed by a nonconstant reference

203

Requires a positive integer constant

204

Failed to access protected class member

205

Import already defined in another way

208

Executable file not created

209

'OnCalculate' entry point not found for the


indicator

210

The continue operation can be used only inside


a loop

211

Error accessing private (closed) class member

213

Method of structure or class is not declared

214

Error accessing private (closed) class method

2000-2016, MetaQuotes Software Corp.

737

Standard Constants, Enumerations and Structures

216

Copying of structures with objects is not


allowed

218

Index out of array range

219

Array initialization in structure or class


declaration not allowed

220

Class constructor cannot have parameters

221

Class destructor can not have parameters

222

Class method or structure with the same name


and parameters have already been declared

223

Operand expected

224

Class method or structure with the same name


exists, but with different parameters
(declaration!=implementation)

225

Imported function is not described

226

ZeroMemory() is not allowed for objects with


protected members or inheritance

227

Ambiguous call of the overloaded function


(exact match of parameters for several
overloads)

228

Variable name expected

229

A reference cannot be declared in this place

230

Already used as the enumeration name

232

Class or structure expected

235

Cannot call 'delete' operator to delete the array

236

Operator ' while' expected

237

Operator 'delete' must have a pointer

238

There is 'default' for this 'switch' already

239

Syntax error

240

Escape-sequence can occur only in strings


(starts with '\')

241

Array required - square bracket '[' does not


apply to an array, or non arrays are passed as
array parameters

242

Can not be initialized through the initialization


sequence

243

Import is not defined

244

Optimizer error on the syntactic tree

2000-2016, MetaQuotes Software Corp.

738

Standard Constants, Enumerations and Structures

245

Declared too many structures (try to simplify


the program)

246

Conversion of the parameter is not allowed

247

Incorrect use of the 'delete' operator

248

It's not allowed to declare a pointer to a


reference

249

It's not allowed to declare a reference to a


reference

250

It's not allowed to declare a pointer to a pointer

251

Structure declaration in the list of parameter is


not allowed

252

Invalid operation of typecasting

253

A pointer can be declared only for a class or


structure

256

Undeclared identifier

257

Executable code optimizer error

258

Executable code generation error

260

Invalid expression for the 'switch' operator

261

Pool of string constants overfilled, simplify


program

262

Cannot convert to enumeration

263

Do not use 'virtual' for data (members of a class


or structure)

264

Cannot call protected method of class

265

Overridden virtual functions return a different


type

266

Class cannot be inherited from a structure

267

Structure cannot be inherited from a class

268

Constructor cannot be virtual (virtual specifier


is not allowed)

269

Method of structure cannot be virtual

270

Function must have a body

271

Overloading of system functions (terminal


functions) is prohibited

272

Const specifier is invalid for functions that are


not members of a class or structure

2000-2016, MetaQuotes Software Corp.

739

Standard Constants, Enumerations and Structures

274

Not allowed to change class members in


constant method

276

Inappropriate initialization sequence

277

Missed default value for the parameter (specific


declaration of default parameters)

278

Overriding the default parameter (different


values in declaration and implementation)

279

Not allowed to call non-constant method for a


constant object

280

An object is necessary for accessing members


(a dot for a non class/structure is specified)

281

The name of an already declared structure


cannot be used in declaration

284

Unauthorized conversion (at closed inheritance)

285

Structures and arrays cannot be used as input


variables

286

Const specifier is not valid for constructor/


destructor

287

Incorrect string expression for a datetime

288

Unknown property (#property)

289

Incorrect value of a property

290

Invalid index for a property in #property

291

Call parameter omitted - <func (x,)>

293

Object must be passed by reference

294

Array must be passed by reference

295

Function was declared as exportable

296

Function was not declared as exportable

297

It is prohibited to export imported function

298

Imported function cannot have this parameter


(prohibited to pass a pointer, class or structure
containing a dynamic array, pointer, class, etc.)

299

Must be a class

300

#import was not closed

302

Type mismatch

303

Extern variable is already initialized

304

No exported function or entry point found

2000-2016, MetaQuotes Software Corp.

740

Standard Constants, Enumerations and Structures

305

Explicit constructor call is not allowed

306

Method was declared as constant

307

Method was not declared as constant

308

Incorrect size of the resource file

309

Incorrect resource name

310

Resource file opening error

311

Resource file reading error

312

Unknown resource type

313

Incorrect path to the resource file

314

The specified resource name is already used

315

Argument expected for the function-like macro

316

Unexpected symbol in macro definition

317

Error in formal parameters of the macro

318

Invalid number of parameters for a macro

319

Too many parameters for a macro

320

Too complex, simplify the macro

321

Parameter for EnumToString() can be only an


enumeration

322

The resource name is too long

323

Unsupported image format (only BMP with 24 or


32 bit color depth is supported)

324

An array cannot be declared in operator

325

The function can be declared only in the global


scope

326

The declaration is not allowed for the current


scope

327

Initialization of static variables with the values


of local variables is not allowed

328

Illegal declaration of an array of objects that do


not have a default constructor

329

Initialization list allowed only for constructors

330

No function definition after initialization list

331

Initialization list is empty

332

Array initialization in a constructor is not


allowed

2000-2016, MetaQuotes Software Corp.

741

Standard Constants, Enumerations and Structures

333

Initializing members of a parent class in the


initialization list is not allowed

334

Expression of the integer type expected

335

Memory required for the array exceeds the


maximum value

336

Memory required for the structure exceeds the


maximum value

337

Memory required for the variables declared on


the global level exceeds the maximum value

338

Memory required for local variables exceeds the


maximum value

339

Constructor not defined

340

Invalid name of the icon file

341

Could not open the icon file at the specified


path

342

The icon file is incorrect and is not of the ICO


format

343

Reinitialization of a member in a class/


structure constructor using the initialization list

344

Initialization of static members in


constructor initialization list is not allowed

345

Initialization of a non-static member of a class/


structure on a global level is not allowed

346

The name of the class/structure method


matches the name of an earlier declared
member

347

The name of the class/structure member


matches the name of an earlier declared
method

348

Virtual function cannot be declared as static

349

The const modifier is not allowed for static


functions

350

Constructor or destructor cannot be static

351

Non-static member/method of a class or a


structure cannot be accessed from a static
function

352

An overload operation (+,-,[],++,-- etc.) is


expected after the operator keyword

353

Not all operations can be overloaded in MQL5

2000-2016, MetaQuotes Software Corp.

the

742

Standard Constants, Enumerations and Structures

354

Definition does not match declaration

355

An invalid number of parameters is specified


for the operator

356

Event handling function not found

357

Method cannot be exported

358

A pointer to the constant object cannot be


normalized by a non-constant object

359

Class templates are not supported yet

360

Function template overload is not supported yet

361

Function template cannot be applied

362

Ambiguous parameter in function template


(several parameter types can be applied)

363

Unable to determine the parameter type, by


which the function template argument should be
normalized

364

Incorrect number of parameters in the function


template

365

Function template cannot be virtual

366

Function templates cannot be exported

367

Function templates cannot be imported

368

Structures containing the objects


allowed

369

String arrays and structures containing the


objects are not allowed

370

A static class/structure member must be


explicitly initialized

371

Compiler limitation: the string cannot contain


more than 65 535 characters

372

Inconsistent #ifdef/#endif

373

Object of class cannot be returned, copy


constructor not found

374

Non-static members and methods cannot be


used

375

OnTesterInit() impossible
OnTesterDeinit()

376

Redefinition of formal parameter '%s'

377

Macro __FUNCSIG__ and __FUNCTION__ cannot


appear outside of a function body

2000-2016, MetaQuotes Software Corp.

to

use

are not

without

743

Standard Constants, Enumerations and Structures

378

Invalid returned type. For example, this error


will be produced for functions imported from
DLL that return structure or pointer.

379

Template usage error

380

Not used

381

Illegal syntax when declaring pure virtual


function, only "=NULL" or "=0" are allowed

382

Only virtual functions can be declared with the


pure-specifier ("=NULL" or "=0")

383

Abstract class cannot be instantiated

2000-2016, MetaQuotes Software Corp.

744

Standard Constants, Enumerations and Structures

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

Unexpected internal error

ERR_WRONG_INTERNAL_PARA
METER

4002

Wrong parameter in the inner


call of the client terminal
function

ERR_INVALID_PARAMETER

4003

Wrong parameter when calling


the system function

ERR_NOT_ENOUGH_MEMORY

4004

Not enough memory


to
perform the system function

ERR_STRUCT_WITHOBJECTS_
ORCLASS

4005

The structure contains objects


of strings and/or dynamic
arrays and/or structure of
such objects and/or classes

ERR_INVALID_ARRAY

4006

Array of a wrong type, wrong


size, or a damaged object of a
dynamic array

ERR_ARRAY_RESIZE_ERROR

4007

Not enough memory for the


relocation of an array, or an
attempt to change the size of
a static array

ERR_STRING_RESIZE_ERROR

4008

Not enough memory for the


relocation of string

ERR_NOTINITIALIZED_STRING

4009

Not initialized string

ERR_INVALID_DATETIME

4010

Invalid date and/or time

ERR_ARRAY_BAD_SIZE

4011

Requested array size exceeds


2 GB

ERR_INVALID_POINTER

4012

Wrong pointer

ERR_INVALID_POINTER_TYPE

4013

Wrong type of pointer

ERR_FUNCTION_NOT_ALLOWE
D

4014

Function is not allowed for call

ERR_RESOURCE_NAME_DUPLIC
ATED

4015

The names of the dynamic and


the static resource match

ERR_RESOURCE_NOT_FOUND

4016

Resource with this name has


not been found in EX5

2000-2016, MetaQuotes Software Corp.

completed

745

Standard Constants, Enumerations and Structures

ERR_RESOURCE_UNSUPPOTED
_TYPE

4017

Unsupported resource type or


its size exceeds 16 Mb

ERR_RESOURCE_NAME_IS_TO
O_LONG

4018

The resource name exceeds 63


characters

ERR_CHART_WRONG_ID

4101

Wrong chart ID

ERR_CHART_NO_REPLY

4102

Chart does not respond

ERR_CHART_NOT_FOUND

4103

Chart not found

ERR_CHART_NO_EXPERT

4104

No Expert Advisor in the chart


that could handle the event

ERR_CHART_CANNOT_OPEN

4105

Chart opening error

ERR_CHART_CANNOT_CHANG
E

4106

Failed to change chart symbol


and period

ERR_CHART_WRONG_PARAME
TER

4107

Error value of the parameter


for the function of working
with charts

ERR_CHART_CANNOT_CREATE
_TIMER

4108

Failed to create timer

ERR_CHART_WRONG_PROPER
TY

4109

Wrong chart property ID

ERR_CHART_SCREENSHOT_FAI
LED

4110

Error creating screenshots

ERR_CHART_NAVIGATE_FAILE
D

4111

Error navigating through chart

ERR_CHART_TEMPLATE_FAILE
D

4112

Error applying template

ERR_CHART_WINDOW_NOT_F
OUND

4113

Subwindow containing
indicator was not found

ERR_CHART_INDICATOR_CANN
OT_ADD

4114

Error adding an indicator to


chart

ERR_CHART_INDICATOR_CANN
OT_DEL

4115

Error deleting an
from the chart

ERR_CHART_INDICATOR_NOT_
FOUND

4116

Indicator not found on the


specified chart

ERR_OBJECT_ERROR

4201

Error working with a graphical


object

ERR_OBJECT_NOT_FOUND

4202

Graphical object was not found

Charts

the

indicator

Graphical Objects

2000-2016, MetaQuotes Software Corp.

746

Standard Constants, Enumerations and Structures

ERR_OBJECT_WRONG_PROPER
TY

4203

Wrong ID of a graphical object


property

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

Symbol is not selected


MarketWatch

ERR_MARKET_WRONG_PROPE
RTY

4303

Wrong identifier of a symbol


property

ERR_MARKET_LASTTIME_UNKN
OWN

4304

Time of the last tick is not


known (no ticks)

ERR_MARKET_SELECT_ERROR

4305

Error adding or deleting a


symbol in MarketWatch

ERR_HISTORY_NOT_FOUND

4401

Requested history not found

ERR_HISTORY_WRONG_PROPE
RTY

4402

Wrong ID
property

ERR_GLOBALVARIABLE_NOT_F
OUND

4501

Global variable of the client


terminal is not found

ERR_GLOBALVARIABLE_EXISTS

4502

Global variable of the client


terminal with the same name
already exists

ERR_MAIL_SEND_FAILED

4510

Email sending failed

ERR_PLAY_SOUND_FAILED

4511

Sound playing failed

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

File sending via ftp failed

ERR_NOTIFICATION_SEND_FAI
LED

4515

Failed to send a notification

ERR_NOTIFICATION_WRONG_P
ARAMETER

4516

Invalid parameter for sending


a notification an empty
string or NULL has been

MarketInfo

in

History Access

of

the

history

Global_Variables

2000-2016, MetaQuotes Software Corp.

747

Standard Constants, Enumerations and Structures

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

FTP server is not specified

ERR_FTP_NOLOGIN

4520

FTP login is not specified

ERR_FTP_FILE_ERROR

4521

File not found in the MQL5


\Files directory to send on FTP
server

ERR_FTP_CONNECT_FAILED

4522

FTP connection failed

ERR_FTP_CHANGEDIR

4523

FTP path not found on server

ERR_FTP_CLOSED

4524

FTP connection closed

ERR_BUFFERS_NO_MEMORY

4601

Not enough memory for the


distribution
of
indicator
buffers

ERR_BUFFERS_WRONG_INDEX

4602

Wrong indicator buffer index

4603

Wrong ID of the
indicator property

ERR_ACCOUNT_WRONG_PROP
ERTY

4701

Wrong account property ID

ERR_TRADE_WRONG_PROPER
TY

4751

Wrong trade property ID

ERR_TRADE_DISABLED

4752

Trading by Expert Advisors


prohibited

ERR_TRADE_POSITION_NOT_F
OUND

4753

Position not found

ERR_TRADE_ORDER_NOT_FOU
ND

4754

Order not found

ERR_TRADE_DEAL_NOT_FOUN
D

4755

Deal not found

ERR_TRADE_SEND_FAILED

4756

Trade request sending failed

sending

of

Custom Indicator Buffers

Custom Indicator Properties


ERR_CUSTOM_WRONG_PROPE
RTY

custom

Account

2000-2016, MetaQuotes Software Corp.

748

Standard Constants, Enumerations and Structures

Indicators
ERR_INDICATOR_UNKNOWN_S
YMBOL

4801

Unknown symbol

ERR_INDICATOR_CANNOT_CRE
ATE

4802

Indicator cannot be created

ERR_INDICATOR_NO_MEMORY

4803

Not enough memory to add the


indicator

ERR_INDICATOR_CANNOT_APP
LY

4804

The indicator cannot be


applied to another indicator

ERR_INDICATOR_CANNOT_ADD

4805

Error applying an indicator to


chart

ERR_INDICATOR_DATA_NOT_F
OUND

4806

Requested data not found

ERR_INDICATOR_WRONG_HAN
DLE

4807

Wrong indicator handle

ERR_INDICATOR_WRONG_PAR
AMETERS

4808

Wrong number of parameters


when creating an indicator

ERR_INDICATOR_PARAMETERS
_MISSING

4809

No parameters when creating


an indicator

ERR_INDICATOR_CUSTOM_NA
ME

4810

The first parameter in the


array must be the name of the
custom indicator

ERR_INDICATOR_PARAMETER_
TYPE

4811

Invalid parameter type in the


array
when creating
an
indicator

ERR_INDICATOR_WRONG_INDE
X

4812

Wrong index of the requested


indicator buffer

ERR_BOOKS_CANNOT_ADD

4901

Depth Of Market can not be


added

ERR_BOOKS_CANNOT_DELETE

4902

Depth Of Market can not be


removed

ERR_BOOKS_CANNOT_GET

4903

The data from Depth Of


Market can not be obtained

ERR_BOOKS_CANNOT_SUBSCRI
BE

4904

Error in subscribing to receive


new data from Depth Of
Market

5001

More than 64 files cannot be


opened at the same time

Depth of Market

File Operations
ERR_TOO_MANY_FILES

2000-2016, MetaQuotes Software Corp.

749

Standard Constants, Enumerations and Structures

ERR_WRONG_FILENAME

5002

Invalid file name

ERR_TOO_LONG_FILENAME

5003

Too long file name

ERR_CANNOT_OPEN_FILE

5004

File opening error

ERR_FILE_CACHEBUFFER_ERR
OR

5005

Not enough memory for cache


to read

ERR_CANNOT_DELETE_FILE

5006

File deleting error

ERR_INVALID_FILEHANDLE

5007

A file with this handle was


closed, or was not opening at
all

ERR_WRONG_FILEHANDLE

5008

Wrong file handle

ERR_FILE_NOTTOWRITE

5009

The file must be opened for


writing

ERR_FILE_NOTTOREAD

5010

The file must be opened for


reading

ERR_FILE_NOTBIN

5011

The file must be opened as a


binary one

ERR_FILE_NOTTXT

5012

The file must be opened as a


text

ERR_FILE_NOTTXTORCSV

5013

The file must be opened as a


text or CSV

ERR_FILE_NOTCSV

5014

The file must be opened as


CSV

ERR_FILE_READERROR

5015

File reading error

ERR_FILE_BINSTRINGSIZE

5016

String size must be specified,


because the file is opened as
binary

ERR_INCOMPATIBLE_FILE

5017

A text file must be for string


arrays, for other arrays binary

ERR_FILE_IS_DIRECTORY

5018

This is not a file, this is a


directory

ERR_FILE_NOT_EXIST

5019

File does not exist

ERR_FILE_CANNOT_REWRITE

5020

File can not be rewritten

ERR_WRONG_DIRECTORYNAM
E

5021

Wrong directory name

ERR_DIRECTORY_NOT_EXIST

5022

Directory does not exist

ERR_FILE_ISNOT_DIRECTORY

5023

This is a file, not a directory

ERR_CANNOT_DELETE_DIRECT

5024

The

2000-2016, MetaQuotes Software Corp.

directory

cannot

be

750

Standard Constants, Enumerations and Structures

ORY

removed

ERR_CANNOT_CLEAN_DIRECT
ORY

5025

Failed to clear the directory


(probably one or more files are
blocked and removal operation
failed)

ERR_FILE_WRITEERROR

5026

Failed to write a resource to a


file

ERR_FILE_ENDOFFILE

5027

Unable to read the next piece


of data from a CSV file
(FileReadString,
FileReadNumber,
FileReadDatetime,
FileReadBool), since the end of
file is reached

ERR_NO_STRING_DATE

5030

No date in the string

ERR_WRONG_STRING_DATE

5031

Wrong date in the string

ERR_WRONG_STRING_TIME

5032

Wrong time in the string

ERR_STRING_TIME_ERROR

5033

Error converting string to date

ERR_STRING_OUT_OF_MEMOR
Y

5034

Not enough memory for the


string

ERR_STRING_SMALL_LEN

5035

The string length is less than


expected

ERR_STRING_TOO_BIGNUMBER

5036

Too large number, more than


ULONG_MAX

ERR_WRONG_FORMATSTRING

5037

Invalid format string

ERR_TOO_MANY_FORMATTER
S

5038

Amount of format specifiers


more than the parameters

ERR_TOO_MANY_PARAMETERS

5039

Amount of parameters more


than the format specifiers

ERR_WRONG_STRING_PARAME
TER

5040

Damaged parameter of string


type

ERR_STRINGPOS_OUTOFRANG
E

5041

Position outside the string

ERR_STRING_ZEROADDED

5042

0 added to the string end, a


useless operation

ERR_STRING_UNKNOWNTYPE

5043

Unknown data type


converting to a string

ERR_WRONG_STRING_OBJECT

5044

Damaged string object

String Casting

2000-2016, MetaQuotes Software Corp.

when

751

Standard Constants, Enumerations and Structures

Operations with Arrays


ERR_INCOMPATIBLE_ARRAYS

5050

Copying incompatible arrays.


String array can be copied only
to a string array, and a
numeric array - in numeric
array only

ERR_SMALL_ASSERIES_ARRAY

5051

The receiving array is declared


as AS_SERIES, and it is of
insufficient size

ERR_SMALL_ARRAY

5052

Too small array, the starting


position is outside the array

ERR_ZEROSIZE_ARRAY

5053

An array of zero length

ERR_NUMBER_ARRAYS_ONLY

5054

Must be a numeric array

ERR_ONEDIM_ARRAYS_ONLY

5055

Must be a one-dimensional
array

ERR_SERIES_ARRAY

5056

Timeseries cannot be used

ERR_DOUBLE_ARRAY_ONLY

5057

Must be an array of type


double

ERR_FLOAT_ARRAY_ONLY

5058

Must be an array of type float

ERR_LONG_ARRAY_ONLY

5059

Must be an array of type long

ERR_INT_ARRAY_ONLY

5060

Must be an array of type int

ERR_SHORT_ARRAY_ONLY

5061

Must be an array of type short

ERR_CHAR_ARRAY_ONLY

5062

Must be an array of type char

ERR_OPENCL_NOT_SUPPORTE
D

5100

OpenCL functions are not


supported on this computer

ERR_OPENCL_INTERNAL

5101

Internal error occurred when


running OpenCL

ERR_OPENCL_INVALID_HANDL
E

5102

Invalid OpenCL handle

ERR_OPENCL_CONTEXT_CREA
TE

5103

Error creating
context

ERR_OPENCL_QUEUE_CREATE

5104

Failed to create a run queue in


OpenCL

ERR_OPENCL_PROGRAM_CREA
TE

5105

Error occurred when compiling


an OpenCL program

ERR_OPENCL_TOO_LONG_KER
NEL_NAME

5106

Too long kernel name (OpenCL


kernel)

Operations with OpenCL

2000-2016, MetaQuotes Software Corp.

the

OpenCL

752

Standard Constants, Enumerations and Structures

ERR_OPENCL_KERNEL_CREATE

5107

Error creating
kernel

an

OpenCL

ERR_OPENCL_SET_KERNEL_PA
RAMETER

5108

Error occurred when setting


parameters for the OpenCL
kernel

ERR_OPENCL_EXECUTE

5109

OpenCL program runtime error

ERR_OPENCL_WRONG_BUFFER
_SIZE

5110

Invalid size of the OpenCL


buffer

ERR_OPENCL_WRONG_BUFFER
_OFFSET

5111

Invalid offset in the OpenCL


buffer

ERR_OPENCL_BUFFER_CREATE

5112

Failed to create an OpenCL


buffer

ERR_WEBREQUEST_INVALID_A
DDRESS

5200

Invalid URL

ERR_WEBREQUEST_CONNECT_
FAILED

5201

Failed to connect to specified


URL

ERR_WEBREQUEST_TIMEOUT

5202

Timeout exceeded

ERR_WEBREQUEST_REQUEST_
FAILED

5203

HTTP request failed

65536

User defined errors start with


this code

Operations with WebRequest

User-Defined Errors
ERR_USER_ERROR_FIRST

See also
Trade Server Return Codes

2000-2016, MetaQuotes Software Corp.

753

Standard Constants, Enumerations and Structures

Input and Output Constants


Constants:
File opening flags
File properties
Positioning inside a file
Code page usage
MessageBox

2000-2016, MetaQuotes Software Corp.

754

Standard Constants, Enumerations and Structures

File Opening Flags


File opening flag values specify the file access mode. Flags are defined as follows:
Identifier

Value

Description

FILE_READ

File is opened for reading. Flag


is used in FileOpen(). When
opening a file specification of
FILE_WRITE and/or FILE_READ
is required.

FILE_WRITE

File is opened for writing. Flag


is used in FileOpen(). When
opening a file specification of
FILE_WRITE and/or FILE_READ
is required.

FILE_BIN

Binary
read/write
mode
(without string to string
conversion). Flag is used in
FileOpen().

FILE_CSV

CSV file (all its elements are


converted to strings of the
appropriate type, Unicode or
ANSI, and
separated
by
separator). Flag is used in
FileOpen().

FILE_TXT

16

Simple text file (the same as


csv file, but without taking into
account the separators). Flag is
used in FileOpen().

FILE_ANSI

32

Strings of ANSI type (one byte


symbols). Flag is used in
FileOpen().

FILE_UNICODE

64

Strings of UNICODE type (two


byte symbols). Flag is used in
FileOpen().

FILE_SHARE_READ

128

Shared access for reading from


several programs. Flag is used
in FileOpen(), but it does not
replace the necessity
to
indicate FILE_WRITE and/or
the FILE_READ flag when
opening a file.

FILE_SHARE_WRITE

256

Shared access for writing from


several programs. Flag is used
in FileOpen(), but it does not
replace the necessity
to

2000-2016, MetaQuotes Software Corp.

755

Standard Constants, Enumerations and Structures


indicate FILE_WRITE and/or
the FILE_READ flag when
opening a file.
FILE_REWRITE

512

Possibility for the file rewrite


using functions FileCopy() and
FileMove(). The file should
exist or should be opened for
writing, otherwise the file will
not be opened.

FILE_COMMON

4096

The file path in the common


folder of all client terminals
\Terminal\Common\Files. Flag
is
used
in
FileOpen(),
FileCopy(), FileMove() and in
FileIsExist() functions.

One or several flags can be specified when opening a file. This is a combination of flags. The
combination of flags is written using the sign of logical OR (|), which is positioned between
enumerated flags. For example, to open a file in CSV format for reading and writing at the same time,
specify the combination FILE_READ|FILE_WRITE|FILE_CSV.
Example:
int filehandle=FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV);

There are some specific features of work when you specify read and write flags:
If FILE_READ is specified, an attempt is made to open an existing file. If a file does not exist, file

opening fails, a new file is not created.


FILE_READ|FILE_WRITE a new file is created if the file with the specified name does not exist.
FILE_WRITE the file is created again with a zero size.

When opening a file, specification of FILE_WRITE and/or FILE_READ is required.


Flags that define the type of reading of an open file possess priority. The highest flag is FILE_CSV,
then goes FILE_BIN, and FILE_TXT is of lowest priority. Thus, if several flags are specified at the same
time, (FILE_TXT|FILE_CSV or FILE_TXT|FILE_BIN or FILE_BIN|FILE_CSV), the flag with the highest
priority will be used.
Flags that define the type of encoding also have priority. FILE_UNICODE is of a higher priority than
FILE_ANSI. So if you specify combination FILE_UNICODE|FILE_ANSI, flag FILE_UNICODE will be used.
If neither FILE_UNICODE nor FILE_ANSI is indicated, FILE_UNICODE is implied. If neither FILE_CSV, nor
FILE_BIN, nor FILE_TXT is specified, FILE_CSV is implied.
If a file is opened for reading as a text file (FILE_TXT or FILE_CSV), and at the file beginning a special
two-byte indication 0xff,0xfe is found, the encoding flag will be FILE_UNICODE, even if FILE_ANSI is
specified.
See also
File Functions

2000-2016, MetaQuotes Software Corp.

756

Standard Constants, Enumerations and Structures

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

Check the existence

FILE_CREATE_DATE

Date of creation

FILE_MODIFY_DATE

Date of the last modification

FILE_ACCESS_DATE

Date of the last access to the file

FILE_SIZE

File size in bytes

FILE_POSITION

Position of a pointer in the file

FILE_END

Get the end of file sign

FILE_LINE_END

Get the end of line sign

FILE_IS_COMMON

The file is opened in a shared folder of all


terminals (see FILE_COMMON)

FILE_IS_TEXT

The file is opened as a text file (see FILE_TXT)

FILE_IS_BINARY

The file is opened as a binary file (see


FILE_BIN)

FILE_IS_CSV

The file is opened as CSV (see FILE_CSV)

FILE_IS_ANSI

The file is opened as ANSI (see FILE_ANSI)

FILE_IS_READABLE

The opened file is readable (see FILE_READ)

FILE_IS_WRITABLE

The opened file is writable (see FILE_WRITE)

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.

2000-2016, MetaQuotes Software Corp.

757

Standard Constants, Enumerations and Structures

Positioning Inside a File


Most of file functions are associated with data read/write operations. At the same time, using the
FileSeek() you can specify the position of a file pointer to a position inside the file, from which the
next read or write operation will be performed. The ENUM_FILE_POSITION enumeration contains valid
pointer positions, relative to which you can specify the shift in bytes for the next operation.
ENUM_FILE_POSITION
Identifier

Description

SEEK_SET

File beginning

SEEK_CUR

Current position of a file pointer

SEEK_END

File end

See also
FileIsEnding, FileIsLineEnding

2000-2016, MetaQuotes Software Corp.

758

Standard Constants, Enumerations and Structures

Using a Codepage in String Conversion Operations


When converting string variables into arrays of char type and back, the encoding that by default
corresponds to the current ANSI of Windows operating system (CP_ACP) is used in MQL5. If you want
to specify a different type of encoding, it can be set as additional parameter for the
CharArrayToString(), StringToCharArray() and FileOpen() functions.
The table lists the built-in constants for some of the most popular code pages. Not mentioned code
pages can be specified by a code corresponding to the page.
Built-in Constants of Codepages
Constant

Value

Description

CP_ACP

The current Windows


code page.

CP_OEMCP

The current system OEM code


page.

CP_MACCP

The current system Macintosh


code page.
Note: This value is mostly
used in
earlier
created
program codes and is of no
use now, since modern
Macintosh
computers
use
Unicode for encoding.

CP_THREAD_ACP

The Windows ANSI code page


for the current thread.

CP_SYMBOL

42

Symbol code page

CP_UTF7

65000

UTF-7 code page.

CP_UTF8

65001

UTF-8 code page.

See also
Client Terminal Properties

2000-2016, MetaQuotes Software Corp.

ANSI

759

Standard Constants, Enumerations and Structures

Constants of the MessageBox Dialog Window


This section contains return codes of the MessageBox() function. If a message window has a Cancel
button, the function returns IDCANCEL, in case if the ESC key or the Cancel button is pressed. If there
is no Cancel button in the message window, the pressing of ESC does not give any effect.
Constant

Value

Description

IDOK

"OK" button has been pressed

IDCANCEL

"Cancel"
pressed

IDABORT

"Abort"
pressed

IDRETRY

"Retry"
pressed

IDIGNORE

"Ignore"
pressed

IDYES

"Yes" button has been pressed

IDNO

"No" button has been pressed

IDTRYAGAIN

10

"Try Again" button has been


pressed

IDCONTINUE

11

"Continue" button has been


pressed

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

Message window contains only


one button: OK. Default

MB_OKCANCEL

0x00000001

Message window contains two


buttons: OK and Cancel

MB_ABORTRETRYIGNORE

0x00000002

Message window contains


three buttons: Abort, Retry
and Ignore

MB_YESNOCANCEL

0x00000003

Message window contains


three buttons: Yes, No and
Cancel

MB_YESNO

0x00000004

Message window contains two


buttons: Yes and No

2000-2016, MetaQuotes Software Corp.

760

Standard Constants, Enumerations and Structures

MB_RETRYCANCEL

0x00000005

Message window contains two


buttons: Retry and Cancel

MB_CANCELTRYCONTINUE

0x00000006

Message window contains


three buttons: Cancel, Try
Again, Continue

To display an icon in the message window it is necessary to specify additional flags:


Constant

Value

Description

MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND

0x00000010

The STOP sign icon

MB_ICONQUESTION

0x00000020

The question sign icon

MB_ICONEXCLAMATION,
MB_ICONWARNING

0x00000030

The exclamation/warning sign


icon

MB_ICONINFORMATION,
MB_ICONASTERISK

0x00000040

The encircled i sign

Default buttons are defined by the following flags:


Constant

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

The second button is default

MB_DEFBUTTON3

0x00000200

The third button is default

MB_DEFBUTTON4

0x00000300

The fourth button is default

2000-2016, MetaQuotes Software Corp.

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

for imported functions.


Runtime errors getting information about runtime and critical errors.

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.

2000-2016, MetaQuotes Software Corp.

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

A separate thread, the number


of threads for scripts is equal
to the number of scripts

A looped script cannot break


running of other programs

Expert Advisor

A separate thread, the number


of threads for Expert Advisors
is equal to the number of
Expert Advisors

A looped Expert Advisor


cannot break running of other
programs

Indicator

One thread for all indicators


on a symbol. The number of
threads is equal to the number
of symbols with indicators

An infinite loop in one


indicator will stop all other
indicators on this symbol

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

const int reason

Expert Advisors
and indicators

Deinit
handler.

event

void

OnStart

none

scripts

Start

event

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

764

MQL5 programs

double

OnTester

none

Expert Advisors

Tester
handler.

event

void

OnChartEvent

const int id,


const
long
&lparam,
const
double
&dparam,
const
string
&sparam

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.

Functions prohibited in Indicators and Expert Advisors


Indicators, scripts and Expert Advisors are executable programs written in MQL5. They are designed
for different types of tasks. Therefore there are some restrictions on the use of certain functions,
depending on the type of program. The following functions are prohibited in indicators:
OrderCalcMargin();
OrderCalcProfit();
OrderCheck();
OrderSend();
SendFTP();
Sleep();
ExpertRemove();

2000-2016, MetaQuotes Software Corp.

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.

Loading and Unloading of Indicators


Indicators are loaded in the following cases:
an indicator is attached to a chart;
terminal start (if the indicator was attached to the chart prior to the shutdown of the terminal);
loading of a template (if the indicator attached to a chart is specified in the template);
change of a profile (if the indicator is attached to one of the profile charts);
change of a symbol and/or timeframe of a chart, to which the indicator is attached;
after the successful recompilation of an indicator (if the indicator was attached to a chart);
change of input parameters of the indicator.

Indicators are unloaded in the following cases:


when detaching an indicator from a chart;
terminal shutdown (if the indicator was attached to a chart);
loading of a template (if an indicator is attached to a chart);
closing of a chart, to which the indicator was attached;
change of a profile (if the indicator is attached to one of charts of the changed profile);
change of a symbol and/or timeframe of a chart, to which the indicator is attached;
change of input parameters of the indicator.

Loading and Unloading of Expert Advisors


Expert Advisors are loaded in the following cases:

2000-2016, MetaQuotes Software Corp.

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

to the chart before the authorization of the terminal on the server).


Expert Advisors are unloaded in the following cases:
when detaching an Expert Advisor from a chart;
if a new Expert Advisor is attached to a chart, if another Expert Advisor has been attached already,

this Expert Advisor is unloaded.


terminal shutdown (if the Expert Advisor was attached to a chart);
loading of a template (if an Expert Advisor is attached to the chart);
close of a chart, to which the Expert Advisor is attached.
change of a profile (if the Expert Advisor is attached to one of charts of the changed profile);
change of the account to which the terminal is connected (if the Expert Advisor was attached to the

chart before the authorization of the terminal on the server);


calling the ExpertRemove() function.

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.

Loading and Unloading of Scripts


Scripts are loaded immediately after they are attached to a chart and unloaded immediately after they
complete their operation. OnInit() and OnDeinit() are not called for scripts.
When a program is unloaded (deleted from a chart) the client terminal performs deinitialization of
global variables and deletes the events queue. In this case deinitialization means reset of all the
string-type variables, deallocation of dynamical array objects and call of their destructors if they are
available.
For a better understanding of the Expert Advisor operation we recommend to compile the code of the
following Expert Advisor and perform actions of load/unload, template change, symbol change,
timeframe change etc:
Example:
//+------------------------------------------------------------------+
//|

TestExpert.mq5 |

//|

Copyright 2009, MetaQuotes Software Corp. |

//|

https://www.mql5.com |

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

Checking for Permission to Perform Automated Trading


In order to develop a reliable Expert Advisor capable of working without human intervention, it is
necessary to arrange a set of important checks. First, we should programmatically check if trading is
allowed at all. This is a basic check that is indispensable when developing any automated system.

Checking for permission to perform automated trading in the terminal


The terminal settings provide you with an ability to allow or forbid automated trading for all programs.

2000-2016, MetaQuotes Software Corp.

769

MQL5 programs

You can switch automated trading option right on the terminal's Standard panel:

automated trading enabled, trading functions in launched applications are allowed


for use.

automated trading disabled, running applications are unable to execute trading


functions.

Sample check:
if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");

Checking if trading is allowed for a certain running Expert Advisor/script


You can allow or forbid automated trading for a certain program when launching it. To do this, use the
special check box in the program properties.

2000-2016, MetaQuotes Software Corp.

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.

Checking if trading is allowed for the current account


In some cases, any trading operations are disabled for a certain trading account neither manual nor
automated trading can be performed. Sample check when an investor password has been used to
connect to a trading account:
if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
Comment("Trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN),

2000-2016, MetaQuotes Software Corp.

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:",

"\n\'",AccountInfoInteger(ACCOUNT_LOGIN),"\': trading has been disabled - investor mode

AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) may return false in the following cases:


no

connection
to
the
trade
server.
TerminalInfoInteger(TERMINAL_CONNECTED);

That

can

be

checked

trading account switched to read-only mode (sent to the archive);


trading on the account is disabled at the trade server side;
connection to a trading account has been performed in Investor mode.

See also
Client Terminal Properties, Account Properties, Properties of a Running MQL5 Program

2000-2016, MetaQuotes Software Corp.

using

772

MQL5 programs

Client Terminal Events


Init
Immediately after the client terminal loads a program (an Expert Advisor or custom indicator) and
starts the process of initialization of global variables, the Init event will be sent, which will be
processed by OnInit() event handler, if there is such. This event is also generated after a financial
instrument and/or chart timeframe is changed, after a program is recompiled in MetaEditor, after
input parameters are changed from the setup window of an Expert Advisor or a custom indicator. An
Expert Advisor is also initialized after the account is changed. The Init event is not generated for
scripts.

Deinit
Before global variables are deinitialized and the program (Expert Advisor or custom indicator) is
unloaded, the client terminal sends the Deinit event to the program. Deinit is also generated when the
client terminal is closed, when a chart is closed, right before the security and/or timeframe is
changed, at a successful program re-compilation, when input parameters are changed, and when
account is changed.
The deinitialization reason can be obtained from the parameter, passed to the OnDeinit() function.
The OnDeinit() function run is restricted to 2.5 seconds. If during this time the function hasn't been
completed, then it is forcibly terminated. The Deinit event is not generated for scripts.

Start
The Start event is a special event for script activation after it is loaded. This event is processed by
OnStart handler. The Start event is not 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.

2000-2016, MetaQuotes Software Corp.

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

OrderSendAsync functions and its further execution;


Sending a trade request via the terminal graphical interface and its further execution;
Pending orders and stop orders activation on the server;
Performing operations on a trade server side.

The following trade transactions are performed as a result of these actions:


handling a trade request;
changing open orders;
changing orders history;
changing deals history;
changing positions.

For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions. Arrival of such a transaction at the terminal is a
TradeTransaction event. 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.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

creating user interfaces

using graphical objects

OBJ_BITMAP and

PlaySound()
Example of call of the PlaySound() function:
//+------------------------------------------------------------------+
//| Calls standard OrderSend() and plays a sound

//+------------------------------------------------------------------+
void OrderSendWithAudio(MqlTradeRequest

&request, MqlTradeResult &result)

{
//--- send a request to a server
OrderSend(request,result);
//--- if a request is accepted, play sound Ok.wav
if(result.retcode==TRADE_RETCODE_PLACED) PlaySound("Ok.wav");
//--- if fails, play alarm from file timeout.wav
else PlaySound("timeout.wav");
}

The example shows how to play sounds from files 'Ok.wav' and '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.

2000-2016, MetaQuotes Software Corp.

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

// name of the OBJ_BITMAP_LABEL object

string euro

="\\Images\\euro.bmp";

// path to the file terminal_data_directory\MQL5\Images\

string dollar

="\\Images\\dollar.bmp";

// path to the file terminal_data_directory\MQL5\Images\

//+------------------------------------------------------------------+
//| 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)
{

PrintFormat("Failed to download image from file %s. Error code %d",euro,GetLastError())


}
ResetLastError();
//--- download a picture to indicate the "Unpressed" state of the button
set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,1,dollar);
if(!set)

2000-2016, MetaQuotes Software Corp.

777

MQL5 programs
{

PrintFormat("Failed to download image from file %s. Error code %d",dollar,GetLastError(


}

//--- send a command for a chart to refresh so that the button appears immediately without
ChartRedraw(0);
}
else
{
//--- failed to create an object, notify
PrintFormat("Failed to create object OBJ_BITMAP_LABEL. Error code %d",GetLastError());
}
}
//--return(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";

// path to the file terminal_dara_directory\MQL5\Images\

string dollar

="\\Images\\dollar.bmp";

// path to the file terminal_dara_directory\MQL5\Images\

The files are located in the folder terminal_data_directory\MQL5\Images.


Object OBJ_BITMAP_LABEL is actually a button, which displays one of the two images, depending on
the button state (pressed or unpressed): euro.bmp or dollar.bmp.

2000-2016, MetaQuotes Software Corp.

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.

Including resources to executable files during compilation of mql5


programs
An mql5 program may need a lot of different downloadable resources in the form of image and sound
files. In order to eliminate the need to transfer all these files when moving an executable file in MQL5,
the compiler's directive #resource should be used:
#resource path_to_resource_file

The #resource command tells the compiler that the resource at the specified path
path_to_resource_file should be included into the executable EX5 file. Thus all the necessary images
and sounds can be located directly in an EX5 file, so that there is no need to transfer separately the
files used in it, if you want to run the program on a different terminal. Any EX5 file can contain
resources, and any EX5 program can use resources from another EX5 program.
The files in format BMP and WAV are automatically compressed before including them to an EX5 file.
This denotes that in addition to the creation of complete programs in MQL5, using resources also
allows to reduce the total size of necessary files when using graphics and sounds, as compared to the
usual way of MQL5 program writing.
The resource file size must not exceed 16 Mb.

2000-2016, MetaQuotes Software Corp.

779

MQL5 programs

Search for specified resources by a compiler


A resource is inserted using the command #resource "<path to the resource file>"
#resource "<path_to_resource_file>"

The length of the constant string <path_to_resource_file> must not exceed 63 characters.
The compiler searches for a resource at the specified path in the following order:
if the backslash "\" separator (written as "\\") is placed at the beginning of the path, it searches for

the resource relative to the directory terminal_data_directory\MQL5\,


if there is no backslash, it searches for the resource relative to the location of the source file, in

which the resource is written.


The resource path cannot contain the substrings "..\\" and ":\\".
Examples of resource inclusion:
//--- correct specification of resources
#resource "\\Images\\euro.bmp" // euro.bmp is located in terminal_data_directory\MQL5\Images\
#resource "picture.bmp"

// picture.bmp is located in the same directory as the source file

#resource "Resource\\map.bmp"

// the resource is located in source_file_directory\Resource\map.bmp

//--- incorrect specification of resources


#resource ":picture_2.bmp"

// must not contain ":"

#resource "..\\picture_3.bmp"

// must not contain ".."

#resource "\\Files\\Images\\Folder_First\\My_panel\\Labels\\too_long_path.bmp" //more than 63 symbo

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 name - Images\euro.bmp

#resource "picture.bmp"

// resource name - picture.bmp

#resource "Resource\\map.bmp"

// resource name - Resource\map.bmp

#resource "\\Files\\Pictures\\good.bmp" // resource name - Files\Pictures\good.bmp


#resource "\\Files\\Demo.wav";

// resource name - Files\Demo.wav"

#resource "\\Sounds\\thrill.wav";

// resource name - Sounds\thrill.wav"

...
//--- utilization of resources

2000-2016, MetaQuotes Software Corp.

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

// euro.bmp is located in terminal_data_directory\MQL5\Images\

#resource "\\Images\\dollar.bmp";

// dollar.bmp is located in terminal_data_directory\MQL5\Images\

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:

Using the resources of other mql5 programs


There is another advantage of using resources in any MQL5 program, resources of another EX5 file
can be used. Thus the resources from one EX5 file can be used in many other mql5 programs.
In order to use a resource name from another file, it should be specified as
<path_EX5_file_name>::<resource_name>. For example, suppose the Draw_Triangles_Script.mq5
script contains a resource to an image in the file triangle.bmp:
#resource "\\Files\\triangle.bmp"

Then its name, for using in the script itself, will look like "Files\triangle.bmp", and in order to use it,
"::" should be added to the resource name.

2000-2016, MetaQuotes Software Corp.

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

Working with custom indicators included as resources


One or several custom indicators may be necessary for the operation of MQL5 applications. All of them
can be included into the code of an executable MQL5 program. Inclusion of indicators as resources
simplifies the distribution of applications.
Below is an example of including and using SampleIndicator.ex5 custom indicator located in
terminal_data_folder\MQL5\Indicators\ directory:
//+------------------------------------------------------------------+
//|

SampleEA.mq5 |

//|

Copyright 2013, MetaQuotes Software Corp. |

//|

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

2000-2016, MetaQuotes Software Corp.

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 |

//|

Copyright 2013, MetaQuotes Software Corp. |

//|

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

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

2000-2016, MetaQuotes Software Corp.

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

//--- substring not found - error


if(pos<0)
return(NULL);
//--- skip "\MQL5" directory
pos+=5;
//--- skip extra '\' symbols
while(StringGetCharacter(path,pos+1)=='\\')
pos++;
//--- if this is a resource, return the path relative to MQL5 directory
if(StringFind(path,"::",pos)>=0)
return(StringSubstr(path,pos));
//--- find a separator for the first MQL5 subdirectory (for example, MQL5\Indicators)
//--- if not found, return the path relative to MQL5 directory
if((pos2=StringFind(path,"\\",pos+1))<0)
return(StringSubstr(path,pos));
//--- return the path relative to the subdirectory (for example, MQL5\Indicators)
return(StringSubstr(path,pos2+1));
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function

//+------------------------------------------------------------------+
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

2000-2016, MetaQuotes Software Corp.

784

MQL5 programs

Call of Imported Functions


To import functions during the execution of a mql5-program, the client terminal uses early binding.
This means that if a program has call of an imported function, the corresponding module (ex5 or dll) is
loaded during the program load. MQL5 and DLL libraries are executed in the thread of a calling
module.
It is not recommended to use the fully specified name of the module to be loaded like Drive:\Directory
\FileName.Ext. The MQL5 libraries are loaded from the terminal_dir\MQL5\Libraries folder. If the
library hasn't been found, then the client terminal performs an attempt to load it from terminal_dir
\experts folder.
The system libraries (DLL) are loaded by the operating system rules. If the library is already loaded
(for example, another Expert Advisor, and even from another client terminal, running in parallel), then
it uses requests to the library already loaded. Otherwise, it performs a search in the following
sequence:
1. Directory, from which the module importing dll was started. The module here is an Expert Advisor,
a script, an indicator or EX5 library;
2. Directory terminal_data_directory\MQL5\Libraries (TERMINAL_DATA_PATH\MQL5\Libraries);
3. Directory, from which the MetaTrader 5 client terminal was started;
4. System directory;
5. Windows directory;
6. Current directory;
7. Directories listed in the PATH system variable.
If the DLL library uses another DLL in its work, the first one cannot be loaded in case when there is no
second DLL.
Before an Expert Advisor (script, indicator) is loaded, a common list of all EX5 library modules is
formed. It's going to be used both from a loaded Expert Advisor (script, indicator) and from libraries
of this list. Thus the one-time loading of many times used EX5 library modules is needed. Libraries
use predefined variables of the Expert Advisor (script, indicator) they were called by.
The imported library EX5 is searched for in the following sequence:
1. Directory, path to which is set relative to the directory of the Expert Advisor (script, indicator) that
imports EX5;
2. Directory terminal_directory\MQL5\Libraries;
3. Directory MQL5\Libraries in the common directory of all MetaTrader 5 client terminals (Common
\MQL5\Libraries).
Functions imported DLL into a mql5-program must ensure the Windows API calls agreement. To ensure
such an agreement, in the source text of programs written in C or C++, use the keyword __stdcall,
which is specific to the Microsoft(r) compilers. This agreement is characterized by the following:
caller (in our case it is a mq5-program) should "see" a prototype of a function called (imported from

the DLL), in order to properly combine parameters to a stack;


caller (in our case it is a mql5-program) puts parameters to the stack in a reverse order, from right

to left - in this order an imported function reads parameters passed to it;


parameters are passed by value, except those explicitly passed by reference (in our case strings)
2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

787

MQL5 programs

Testing Trading Strategies


The idea of automated trading is appealing by the fact that the trading robot can work non-stop for 24
hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free
from any psychological problems. It is sufficient enough to clearly formalize the trading rules and
implement them in the algorithms, and the robot is ready to work tirelessly. But first, you must make
sure that the following two important conditions are met:
The Expert Advisor performs trading operations in accordance with the rules of the trading system;
The trading strategy, implemented in the EA, demonstrates a profit on the history.

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

Function Limitations in the Strategy Tester


There are operation limitations for some functions in the client terminal's Strategy Tester.

The Print() and PrintFormat() Functions


To increase performance, Print() and PrintFormat() functions are not executed when optimizing the

2000-2016, MetaQuotes Software Corp.

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 Alert(), MessageBox(), PlaySound(), SendFTP(), SendMail(), SendNotification() and WebRequest()


functions designed for interaction with the "outside world" are not executed in the Strategy Tester.

Tick Generation Modes


An Expert Advisor is a program, written in MQL5, that is run each time in response to some external
event. The EA has a corresponding function (event handler) for each pre-defined event.
The NewTick event (price change) is the main event for the EA and, therefore, we need to generate a
tick sequence to test the EA. There are 3 modes of tick generation implemented in the Strategy Tester
of MetaTrader 5 client terminal:
Every tick
1 Minute OHLC (OHLC prices with minute bars)
Open prices only

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

"1 Minute OHLC"


The "Every tick" mode is the most accurate of the three modes, but at the same time, is the slowest.
The running of the OnTick() handler occurs at every tick, while tick volume can be quite large. For a
strategy, in which the tick sequence of price movement throughout the bar, does not matter, there is
a faster and rougher simulation mode - "1 minute OHLC".
In the "1 minute OHLC" mode, the tick sequence is constructed only by the OHLC prices of the minute
bars, the number of the generated control points is significantly reduced - hence, so is the testing
time. The launch of the OnTick () function is performed on all control points, which are constructed by
the prices of OHLC minute bars.
The refusal to generate additional intermediate ticks between the Open, High, Low, and Close prices,
leads to an appearance of rigid determinism in the development of prices, from the moment that the
Open price is determined. This makes it possible to create a "Testing Grail", which shows a nice
upward graph of the testing balance.
An example of such Grail is presented in the Code Base - Grr-al.

2000-2016, MetaQuotes Software Corp.

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.

"Open Prices Only"


In this mode ticks are generated based on the OHLC prices of the timeframe selected for testing. The
OnTick() function of the Expert Advisor runs only at the beginning of the bar at the Open price. Due to
this feature, stop levels and pending may trigger at a price that differs from the specified one
(especially when testing on higher timeframes). Instead, we have an opportunity to quickly run an
evaluation test of the Expert Advisor.
W1 and MN1 periods are the exceptions in the "Open Price Only" ticks generation mode: for these
timeframes ticks are generated for the OHLC prices of each day, not OHLC prices of the week or
month.
Suppose we test an Expert Advisor on EURUSD H1 in the "Open Prices Only" mode. In this case the
total number of ticks (control points) will be no more than 4*number of one-hour bars within the tested
interval. But the OnTick() handler is called only at the opening of the one-hour bar. The checks
required for a correct testing occur on the rest of the ticks (that are "hidden" from the EA).
The calculation of margin requirements;
2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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

PrintFormat("Error in opening of file %s for writing. Error code=%d",filename,GetLastError())


return;
}
else
{

PrintFormat("The file will be created in %s folder",TerminalInfoString(TERMINAL_COMMONDATA_PA


}

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;

// Period start time

double

// Open price

open;

2000-2016, MetaQuotes Software Corp.

795

MQL5 programs
double

high;

// The highest price of the period

double

low;

// The lowest price of the period

double

close;

// Close price

long

tick_volume;

// Tick volume

int

spread;

// Spread

long

real_volume;

// Trade volume

};

The Global Variables of the Client Terminal


During testing, the global variables of the client terminal are also emulated, but they are not related to
the current global variables of the terminal, which can be seen in the terminal using the F3 button. It
means that all operations with the global variables of the terminal, during testing, take place outside
of the client terminal (in the testing agent).

The Calculation of Indicators During Testing


In the real-time mode, the indicator values are calculated at every tick. The Strategy Tester adopted
a cost-effective model for calculating indicators - indicators are recalculated only immediately before
the running of the EA. It means that the recalculation of the indicators is done before the call of the
OnTick(), OnTrade() and OnTimer() functions.
It does not matter whether or not there is a call for the indicator in a specific event handler. All
the indicators with handles created by the iCustom() or IndicatorCreate() functions will be
recalculated before calling the event handler.
Consequently, when testing in the "Every tick" mode, the calculation of the indicators takes place
before the call of OnTick() function.
If the timer is on in the EA, using the EventSetTimer() function, then the indicators will be
recalculated before each call of the OnTimer() handler. Therefore, the testing time can be greatly
increased with the use of an indicators, written in a non-optimal way.

Loading History during Testing


The history of a symbol to be tested is synchronized and loaded by the terminal from the trade server
before starting the testing process. During the first time, the terminal loads all available history of a
symbol in order not to request it later. Further only the new data are loaded.
A testing agent receives the history of a symbol to be tested from the client terminal right after the
start of testing. If data of other instruments are used in the process of testing (for example, it is a
multicurrency Expert Advisor), the testing agent requests the required history from the client terminal
during the first call to such data. If historical data are available in the terminal, they are immediately
passed to the testing agent. If data are not available, the terminal requests and downloads them from
the server, and then passes to the testing agent.
Data of additional instruments is also required for calculating cross-rates for trade operations. For
example, when testing a strategy on EURCHF with the deposit currency in USD, prior to processing the
first trading operation, the testing agent requests the history data of EURUSD and USDCHF from the
client terminal, though the strategy does not contain direct use call of these symbols.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

Simulation of Time in the Strategy Tester

2000-2016, MetaQuotes Software Corp.

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.

Graphical Objects in Testing


During testing/optimization graphical objects are not plotted. Thus, when referring to the properties
of a created object during testing/optimization, an Expert Advisor will receive zero values.
This limitation does not apply to testing in visual mode.

The OnTimer() Function in the Strategy Tester


MQL5 provides the opportunity for handling timer events. The call of the OnTimer() handler is done
regardless of the test mode. This means that if a test is running in the "Opening prices only" mode for
the period H4, and the EA has a timer set to a call per second, then at the opening of each H4 bar, the
OnTick() handler will be called one time, and the OnTimer() handler will be called 14400 times (3600
seconds * 4 hours ). The amount by which the testing time of the EA will be increased depends on the
logic of the EA.
To check the dependence of the testing time from the given frequency of the timer, we have created a
simple EA without any trading operations.
//--- input parameters
input int

timer=1;

// timer value, sec

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

2000-2016, MetaQuotes Software Corp.

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.

The Sleep() Function in the Strategy Tester


The Sleep() function allows the EA or script to suspend the execution of the mql5-program for a while,
when working on the graph. This can be useful when requesting data, which is not ready at the time of
the request and you need to wait until it is ready. A detailed example of using the Sleep() function can
be found in the section Organizing Data Access.
The testing process is not lingered by the Sleep() calls.When you call the Sleep(), the generated ticks
are "played" within a specified delay, which may result in the triggering of pending orders, stops, etc.
After a Sleep() call, the simulated time in the Strategy Tester increases by an interval, specified in the
parameter of the Sleep function.
If as a result of the execution of the Sleep() function, the current time in the Strategy Tester went
over the testing period, then you will receive an error "Infinite Sleep loop detected while testing". If

2000-2016, MetaQuotes Software Corp.

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.

Using the Strategy Tester


Mathematical Calculations

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.

2000-2016, MetaQuotes Software Corp.

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 |

//|

Copyright 2011, MetaQuotes Software Corp. |

//|

https://www.mql5.com |

//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link

"https://www.mql5.com"

#property version

"1.00"

//--- input parameters


input double

x=-3.0; // start=-3, step=0.05, stop=3

input double

y=-3.0; // start=-3, step=0.05, stop=3

2000-2016, MetaQuotes Software Corp.

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:

2000-2016, MetaQuotes Software Corp.

803

MQL5 programs

The Synchronization of Bars in the "Open prices only" mode


The tester in the MetaTrader 5 client terminal allows us to check the so-called "multi-currency" EAs. A
multi-currency EA - is an EA that trades on two or more symbols.
The testing of strategies, that are trading on multiple symbols, imposes a few additional technical
requirements on the tester:
The generation of ticks for these symbols;
The calculation of indicator values for these symbols;
The calculation of margin requirements for these symbols;
Synchronization of generated tick sequences for all trading symbols.

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

2000-2016, MetaQuotes Software Corp.

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 |

//|

Copyright 2011, MetaQuotes Software Corp. |

//|

https://www.mql5.com |

//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link

"https://www.mql5.com"

#property version

"1.00"

//--- input parameters


input string

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

PrintFormat("The last_bar_time variable is initialized with value %s",TimeToString(last_bar_t

2000-2016, MetaQuotes Software Corp.

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

PrintFormat("A new bar has appeared on symbol %s at %s",_Symbol,TimeToString(TimeCurrent()));


}
//--- open time of the other symbol's bar
datetime other_time;
//--- loop until the open time of other symbol become equal to curr_time

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.

2000-2016, MetaQuotes Software Corp.

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.

The IndicatorRelease() function in the Tester


After completing a single testing, a chart of the instrument is automatically opened, which displays the
completed deals and the indicators used in the EA. This helps to visually check the entry and exit
points, and compare them with the values of the indicators.
Note: indicators, displayed on the chart, which automatically opens after the completion of the
testing, are calculated anew after the completion of testing. Even if these indicators were used in
the tested EA.
But in some cases, the programmer may want to hide the information on which indicators were
involved in the trading algorithms. For example, the code of the EA is rented or sold as an executable
file, without the provision of the source code. For this purpose, the IndicatorRelease() function is
suitable.
If the terminal sets a template with the name tester.tpl in the directory/profiles/templates of the
client terminal, then it will be applied to the opened chart. In its absence, the default template is
applied. (default.tpl).
The IndicatorRelease() function is originally intended for releasing the calculating portion of the
indicator, if it is no longer needed. This allows you to save both the memory and the CPU resources,
because each tick calls for an indicator calculation. Its second purpose is to prohibit the showing of an
indicator on the testing chart, after a single test run.
To prohibit the showing of the indicator on the chart after testing, call the IndicatorRelease() with the
handle of the indicator in the handler OnDeinit(). The OnDeinit() function is always called after the
completion and before the showing of the testing chart.
//+------------------------------------------------------------------+
//| Expert deinitialization function

//+------------------------------------------------------------------+
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().

Event Handling in the Tester


The presence of the OnTick() handler in the EA is not mandatory in order for it to be subjected to
testing on historical data in the MetaTrader 5 tester. It is sufficient enough for the EA ti contain at
least one of the following function-handlers:

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

The Data Exchange between the Terminal and the Agent


When you run a test, the client terminal prepares to send an agent a number of parameter blocks:
Input parameters for testing (simulation mode, the interval of testing, instruments, optimization

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

for setting a StopLoss and Takeprofit, etc)


The Expert Advisor to be tested and the values of its input parameters
Information about additional files (libraries, indicators, data files - # property tester_ ...)

tester_indicator

string

Name of a custom indicator in


the
format
of
"indicator_name.ex5".
Indicators that require testing
are defined automatically from
the call of the iCustom()
function, if the corresponding
parameter is set through a
constant string. For all other
cases
(use
of
the
IndicatorCreate() function or
use of a non-constant string in
the parameter that sets the
indicator name) this property
is required

tester_file

string

File name for a tester with the


indication of extension, in
double quotes (as a constant
string). The specified file will
be passed to tester. Input files
to be tested, if there are

2000-2016, MetaQuotes Software Corp.

809

MQL5 programs

necessary ones, must always


be specified.
tester_library

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.

Using the Shared Folder of All of the Client Terminals


All testing agents are isolated from each other and from the client terminal: each agent has its own
folder in which its logs are recorded. In addition, all file operations during the testing of the agent
occur in the folder agent_name/MQL5/Files. However, we can implement the interaction between the
local agents and the client terminal through a shared folder for all of the client terminals, if during the
file opening you specify the flag FILE_COMMON:

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

812

Predefined Variables

The predefined Variables


For each executable mql5-program a set of predefined variables is supported, which reflect the state
of the current price chart by the moment a mql5-program (Expert Advisor, script or custom indicator)
is started.
Values of predefined variables are set by the client terminal before a mql5-program is started.
Predefined variables are constant and cannot be changed from a mql5-program. As exception, there is
a special variable _LastError, which can be reset to 0 by the ResetLastError function.
Variable

Value

_Digits

Number of decimal places

_Point

Size of the current symbol point in the quote


currency

_LastError

The last error code

_Period

Timeframe of the current chart

_RandomSeed

Current status of the generator of pseudorandom integers

_StopFlag

Program stop flag

_Symbol

Symbol name of the current chart

_UninitReason

Uninitialization reason code

Predefined variables cannot be defined in a library. A library uses such variables that are defined in
program from which this library is called.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

819

Predefined Variables

string _Symbol
The _Symbol variable contains the symbol name of the current chart.
You may also use the Symbol() function.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

821

Common Functions

Common Functions
General-purpose functions not included into any specialized group are listed here.
Function

Action

Alert

Displays a message in a separate window

CheckPointer

Returns the type of the object pointer

Comment

Outputs a comment in the left top corner of the


chart

CryptEncode

Transforms the data from array with the


specified method

CryptDecode

Performs the inverse transformation of the


data from array

DebugBreak

Program breakpoint in debugging

ExpertRemove

Stops Expert Advisor and unloads it from the


chart

GetPointer

Returns the object pointer

GetTickCount

Returns the number of milliseconds that have


elapsed since the system was started

GetMicrosecondCount

Returns the number of microseconds that have


elapsed since the start of MQL5 program

MessageBox

Creates, displays a message box and manages


it

PeriodSeconds

Returns the number of seconds in the period

PlaySound

Plays a sound file

Print

Displays a message in the log

PrintFormat

Formats and prints the sets of symbols and


values in a log file in accordance with a preset
format

ResetLastError

Sets the value of a predetermined variable


_LastError to zero

ResourceCreate

Creates an image resource based on a data set

ResourceFree

Deletes dynamically created resource (freeing


the memory allocated for it)

ResourceReadImage

Reads data from the graphical resource created


by ResourceCreate() function or saved in EX5
file during compilation

ResourceSave

Saves a resource into the specified file

SendFTP

Sends a file at the address specified in the

2000-2016, MetaQuotes Software Corp.

822

Common Functions

settings window of the "FTP" tab


SendMail

Sends an email at the address specified in the


settings window of the "Email" tab

SendNotification

Sends push notifications to mobile terminals,


whose MetaQuotes ID are specified in the
"Notifications" tab

Sleep

Suspends execution of the current Expert


Advisor or script within a specified interval

TerminalClose

Commands the terminal to complete operation

TesterStatistics

It returns the value of a specified statistic


calculated based on testing results

WebRequest

Sends HTTP request to the specified server

ZeroMemory

Resets a variable passed to it by reference. The


variable can be of any type, except for classes
and structures that have constructors.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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");
}
//--}

2000-2016, MetaQuotes Software Corp.

825

Common Functions

See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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 |

//|

Copyright 2009, MetaQuotes Software Corp. |

//|

https://www.mql5.com |

//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link

"https://www.mql5.com"

#property version

"1.00"

input int ticks_to_close=20;// number of ticks before EA unload


//+------------------------------------------------------------------+
//| Expert deinitialization function

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--Print(TimeCurrent(),": " ,__FUNCTION__," reason code = ",reason);
//--- "clear" comment
Comment("");
//--}
//+------------------------------------------------------------------+
//| Expert tick function

//+------------------------------------------------------------------+
void OnTick()
{
static int tick_counter=0;
//--tick_counter++;
Comment("\nBefore unloading expert advisor ",__FILE__," left",
(ticks_to_close-tick_counter)," ticks");
//--- before
if(tick_counter>=ticks_to_close)
{

2000-2016, MetaQuotes Software Corp.

832

Common Functions
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}
Print("tick_counter =",tick_counter);
//--}
//+------------------------------------------------------------------+

See also
Program running, Client terminal events

2000-2016, MetaQuotes Software Corp.

833

Common Functions

GetPointer
The function returns the object pointer.
void* GetPointer(
any_class anyobject

// object of any class

);

Parameters
anyobject
[in] Object of any class.
Return Value
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 |

//|

Copyright 2009, MetaQuotes Software Corp. |

//|

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

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

2000-2016, MetaQuotes Software Corp.

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

Initialize(int id,string comm) { m_id=id; m_comment=comm; }

void

PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }

int

Identifier() { return(m_id); }

CItem*

Next() {return(m_next); }

void

Next(CItem *item) { m_next=item; }

};
//+------------------------------------------------------------------+
//| Simplest class of the list

//+------------------------------------------------------------------+
class CMyList
{
CItem*

m_items;

public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool

InsertToBegin(CItem* item);

void

Destroy();

};
//+------------------------------------------------------------------+
//| 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)

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

836

Common Functions
}

See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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;

//--- number of measurements


for(int count=0;count<1000;count++)
{
uint

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

//--- execute code


Test();
//--- add measurement result (depending on type)

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

// defines set of buttons in the box

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.

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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)

2000-2016, MetaQuotes Software Corp.

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

(now the value of b after subtracting epsilon cannot be rounded to 2

// Print(DoubleToString(b,16))=199.9999999999998578
//

(now the value of b after subtracting epsilon cannot be rounded to 200)

See also
DoubleToString, StringFormat

2000-2016, MetaQuotes Software Corp.

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

...

// values of simple types

);

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

2000-2016, MetaQuotes Software Corp.

Default Behavior

846

Common Functions

(minus)

Left justification within the


set width

Right justification

+ (plus)

Output of the + or - sign for


values of sign types

The sign is shown only if the


value is negative

0 (zero)

Zeroes are added before an


output value within the
preset width. If 0 flag is
specified with an integer
format (i, u, x, X, o, d) and
accuracy specification is set
(for example, %04.d), then 0
is ignored.

Nothing is added

space

A space is shown before an


output value, if it is a sign
and positive value

Spaces aren't inserted

If used together with the


format o, x or X, then before
the output value 0, 0x or 0X is
added respectively.

Nothing is added

If used together with the


format e, E, a or A, value is
always shown with a decimal
point.

Decimal point is shown only if


there is a non-zero fractional
part.

If used together with the


format g or G, flag defines
presence of a decimal point in
the output value and prevents
the cutting off of leading
zeroes.
Flag # is ignored when used
together with formats c, d, i,
u, s.

Decimal point is shown only if


there is a non-zero fractional
part. Leading zeroes are cut
off.

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

Accuracy specification sets


the number of digits after a
decimal point.

c, C

Not used

d, i, u, o, x, X

Sets minimal number of


output digits. If number of
digits in a corresponding
parameter is less than this
accuracy, zeroes are added to
the left of the output value.
The output value isn't cut off,
if the number of output digits
is larger than the specified
accuracy.

e, E, f

Sets number of output digits


after a decimal point. The
last digit is rounded off.

g, G

Sets maximal number


meaningful numbers.

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.

Default accuracy 6. If set


accuracy is 0 or decimal part is
absent, the decimal point is
not shown.
6 meaningful numbers
output.

The whole string is output.

h | l | ll | I32 | I64
Specification of data sizes, passed as a parameter.
Parameter Type

Used Prefix

Joint Specifier of Type

int

l (lower case L)

d, i, o, x, or X

uint

l (lower case L)

o, u, x, or X

long

ll (two lower case L)

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

2000-2016, MetaQuotes Software Corp.

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

Symbol of char type (ANSI)

int

Signed decimal integer

int

Signed decimal integer

int

Unsigned octal integer

int

Unsigned decimal integer

int

Unsigned
hexadecimal
integer, using "abcdef"

int

Unsigned
hexadecimal
integer, using "ABCDEF"

double

A real value in the format [-]


d.dddde[sign] ddd, where d one decimal digit, dddd - one
or more decimal digits, ddd a three-digit number that
determines the size of the
exponent, sign - plus or minus

double

Similar to the format of e,


except that the sign of
exponent is output by upper
case letter (E instead of e)

double

A real value in the format [-]


dddd.dddd, where dddd - one
or more decimal digits.
Number of displayed digits
before the decimal point
depends on the size of
number value. Number of
digits after the decimal point
depends on the required
accuracy.

2000-2016, MetaQuotes Software Corp.

short

type

849

Common Functions

double

A real value output in f or e


format depending on what
output is more compact.

double

A real value output in F or E


format depending on what
output is more compact.

double

A real number in format []


0xh.hhhh pdd, where h.hhhh
mantissa in the form of
hexadecimal digits, using
"abcdef", dd - One or more
digits of exponent. Number of
decimal places is determined
by the accuracy specification

double

A real number in format []


0xh.hhhh Pdd, where h.hhhh
mantissa in the form of
hexadecimal digits, using
"ABCDEF", dd - One or more
digits of exponent. Number of
decimal places is determined
by the accuracy specification

string

String output

Instead of PrintFormat() you can use printf().


Example:

2000-2016, MetaQuotes Software Corp.

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)

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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

// A relative path to the file

);

Creating a resource based on the array of pixels


bool ResourceCreate(
const string

resource_name,

// Resource name

const uint&

data[],

// Data set as an array

uint

img_width,

uint

img_height,

uint

data_xoffset,

// The horizontal rightward offset of the upper left corn

uint

data_yoffset,

// The vertical downward offset of the upper left corner

uint

data_width,

ENUM_COLOR_FORMAT color_format

// The width of the image resource

// The height of the image resource

// The total width of the image based on the data set


// Color processing method

);

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.

2000-2016, MetaQuotes Software Corp.

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

The component of the alpha channel is ignored

COLOR_FORMAT_ARGB_RAW

Color components are not handled by the


terminal (must be correctly set by the user)

COLOR_FORMAT_ARGB_NORMALIZE

Color components are handled by the terminal

See also
Resources, ObjectCreate(), ObjectSetString(), OBJPROP_BMPFILE

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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,

// graphical resource name for reading


// array for receiving data from the resource

// for receiving the image width in the resource


// for receiving the image height in the resource

);

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

2000-2016, MetaQuotes Software Corp.

856

Common Functions

ResourceSave
Saves a resource into the specified file.
bool ResourceSave(
const string resource_name

// Resource name

const string file_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

2000-2016, MetaQuotes Software Corp.

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
*/
}

2000-2016, MetaQuotes Software Corp.

858

Common Functions

SendFTP
Sends a file at the address, specified in the setting window of the "FTP" tab.
bool SendFTP(
string filename,

// file to be send by ftp

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.

2000-2016, MetaQuotes Software Corp.

859

Common Functions

SendNotification
Sends push notifications to the mobile terminals, whose MetaQuotes IDs are specified in the
"Notifications" tab.
bool SendNotification(
string text

// Text of the notification

);

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

862

Common Functions

TerminalClose
The function commands the terminal to complete operation.
bool TerminalClose(
int ret_code

// closing code of the client terminal

);

Parameters
ret_code
[in] Return code, returned by the process of the client terminal at the operation completion.
Return Value
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

tiks_before=500; // number of ticks till termination

input int

pips_to_go=15;

// distance in pips

input int

seconds_st=50;

// number of seconds given to the Expert Advisor

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

2000-2016, MetaQuotes Software Corp.

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

// exit by tick counter

if(distance>pips_to_go)
TerminalClose(1);

// go up by the number of pips equal to pips_to_go

if(distance<-pips_to_go)
TerminalClose(-1);

// go down by the number of pips equal to pips_to_go

if(tick.time-launch_time>seconds_st)
TerminalClose(100);

// termination by timeout

//--}

See also
Program running, Execution errors, Reasons for deinitialization

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

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

// the sum to withdraw

);

Parameters
money
[in] The sum of money that we need to withdraw (in the deposit currency).
Return Value
If successful, returns true, otherwise - false.

2000-2016, MetaQuotes Software Corp.

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[],

// an array containing server response data

string

&result_headers

// headers of server response

// 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[],

// the array of the HTTP message body

char

&result[],

// an array containing server response data

string

&result_headers

// headers of server response

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

2000-2016, MetaQuotes Software Corp.

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

2000-2016, MetaQuotes Software Corp.

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

An example of using the second version of the WebRequest() function:


#property link

"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

="";

//Your MQL5.com account

input string InpPassword="";

//Your account password

input string InpFileName="EURUSDM5.png"; //An image in folder MQL5/Files/


input string InpFileType="image/png";

//Correct mime type of the image

//+------------------------------------------------------------------+
//| 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;

// To receive the operation execution result

char

data[];

// Data array to send POST requests

char

file[];

// Read the image here

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

2000-2016, MetaQuotes Software Corp.

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

str+="Content-Disposition: form-data; name=\"attachedFile_imagesLoader\"; filename=\""+filena


str+="Content-Type: "+filetype+"\r\n\r\n";
res =StringToCharArray(str,data);
res+=ArrayCopy(data,file,res-1,0);
res+=StringToCharArray("\r\n--"+sep+"--\r\n",data,res-1);
ArrayResize(data,ArraySize(data)-1);

2000-2016, MetaQuotes Software Corp.

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

Print("Error sending a file to the server #"+(string)res+", LastError="+(string)GetLastErr


return(false);
}
//--- Receive a link to the image uploaded to the server
str=CharArrayToString(data);
if(StringFind(str,"{\"Url\":\"")==0)
{
res

=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

2000-2016, MetaQuotes Software Corp.

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"

"(This message has been posted by the WebRequest.mq5 script)",InpFileName,InpFile


}
//+------------------------------------------------------------------+

2000-2016, MetaQuotes Software Corp.

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.

2000-2016, MetaQuotes Software Corp.

873

Array Functions

Group of Functions for Working with Arrays


Arrays are allowed to be maximum four-dimensional. Each dimension is indexed from 0 to
dimension_size-1. In a particular case of a one-dimensional array of 50 elements, calling of the first
element will appear as array[0], of the last one - as array[49].
Function

Action

ArrayBsearch

Returns index of the first found element in the


first array dimension

ArrayCopy

Copies one array into another

ArrayCompare

Returns the result of comparing two arrays of


simple types or custom structures without
complex objects

ArrayFree

Frees up buffer of any dynamic array and sets


the size of the zero dimension in 0.

ArrayGetAsSeries

Checks direction of array indexing

ArrayInitialize

Sets all elements of a numeric array into a


single value

ArrayFill

Fills an array with the specified value

ArrayIsSeries

Checks whether an array is a timeseries

ArrayIsDynamic

Checks whether an array is dynamic

ArrayMaximum

Search for an element with the maximal value

ArrayMinimum

Search for an element with the minimal value

ArrayRange

Returns the number of elements


specified dimension of the array

ArrayResize

Sets the new size in the first dimension of the


array

ArraySetAsSeries

Sets the direction of array indexing

ArraySize

Returns the number of elements in the array

ArraySort

Sorting of numeric arrays by the first dimension

2000-2016, MetaQuotes Software Corp.

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 for search


// what is searched for

);

For searching in an array of float type


int ArrayBsearch(
const float&

array[],

float

value

// array for search


// what is searched for

);

For searching in an array of long type


int ArrayBsearch(
const long&

array[],

long

// array for search

value

// what is searched for

);

For searching in an array of int type


int ArrayBsearch(
const int&

array[],

int

// array for search

value

// what is searched for

);

For searching in an array of short type


int ArrayBsearch(
const short&

array[],

short

value

// array for search


// what is searched for

);

For searching in an array of char type


int ArrayBsearch(
const char&
char

array[],

// array for search

value

// what is searched for

);

Parameters
array[]
[in] Numeric array for search.
value

2000-2016, MetaQuotes Software Corp.

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;

// Moving average period

input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE;

// 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';

// Analysis start date

input datetime

InpDateFinish=D'2013.01.01 00:00'; // Analysis finish date

//+------------------------------------------------------------------+
//| Script program start function

//+------------------------------------------------------------------+
void OnStart()
{
double rsi_buff[]; // array of the indicator values
int

size=0;

// array size

//--- receive RSI indicator handle


ResetLastError();
int rsi_handle=iRSI(Symbol(),Period(),InpMAPeriod,InpAppliedPrice);
if(rsi_handle==INVALID_HANDLE)
{
//--- failed to receive the indicator handle
PrintFormat("Indicator handle receiving error. Error code = %d",GetLastError());
return;
}
//--- being in the loop, until the indicator calculates all its values
while(BarsCalculated(rsi_handle)==-1)
{
//--- exit if the indicator has forcedly completed the script's operation
if(IsStopped())
return;
//--- a pause to allow the indicator to calculate all its values
Sleep(10);
}
//--- copy the indicator values for a certain period of time

2000-2016, MetaQuotes Software Corp.

876